【发布时间】:2016-06-22 10:30:27
【问题描述】:
我仍在开发游戏,但遇到了另一个问题,我正在尝试创建一个无限循环,每次执行都会等待几秒钟,我目前有:
StartScript.cs
using UnityEngine;
using System.Collections;
using ProgressBar;
public class StartScript : MonoBehaviour {
private ProgressBarBehaviour hunger;
private ProgressBarBehaviour stamina;
private ProgressRadialBehaviour health;
private ProgressBarBehaviour thirst;
public void OnGUI(){
this.hunger = GameObject.Find("hungerBar").GetComponent<ProgressBarBehaviour>();
this.stamina = GameObject.Find("staminaBar").GetComponent<ProgressBarBehaviour>();
this.health = GameObject.Find("healthBar").GetComponent<ProgressRadialBehaviour>();
this.thirst = GameObject.Find("thirstBar").GetComponent<ProgressBarBehaviour>();
this.health.Value = 100f;
this.stamina.Value = 100f;
StartCoroutine ("runHunger");
}
bool addBar(ProgressBarBehaviour target, float percentage){
Debug.Log (percentage);
if ((target.Value + percentage) <= 100f) {
target.IncrementValue (percentage);
return true;
}
return false;
}
bool damageBar(ProgressBarBehaviour target, float percentage){
if ((target.Value - percentage) >= 0f) {
target.DecrementValue (percentage);
return true;
}
return false;
}
bool addRadial(ProgressRadialBehaviour target, float percentage){
if ((target.Value + percentage) <= 100f) {
target.IncrementValue (percentage);
return true;
}
return false;
}
bool damageRadial(ProgressRadialBehaviour target, float percentage){
if ((target.Value - percentage) >= 0f) {
target.DecrementValue (percentage);
return true;
}
return false;
}
IEnumerator runHunger(){
while (true) {
yield return new WaitForSeconds(10f);
/*if (!this.addBar(this.hunger,5f)) {
this.damageRadial(this.health,3f);
}*/
Debug.Log("Time: "+Time.time);
}
}
IEnumerator runHealth(){
while (true) {
}
}
/*
IEnumerator runThirst(){
while (true) {
if (!this.thirst.Add (2)) {
this.health.Damage(8);
}
}
}*/
}
正如你们所看到的,我正在尝试使用yield return new WaitForSeconds() 创建一个while(true){} 循环,其想法是它每(在此测试用例中)10 秒运行一次循环中的函数。
第一次执行就像一个魅力,它等待 10 秒,但之后它只等待大约 0.1 秒并再次执行。
希望有人能帮我解决这个问题。
【问题讨论】:
-
ciao Giovanniu——永远,永远不要出于任何原因使用“ongui”——它已从 Unity 中删除!只需使用普通的 UI。非常简单,(1)点击“添加画布”(通常选择“缩放到屏幕大小”)。 (2) 点击“添加按钮”。 (3)你完成了..回家去老婆和酒!
标签: c# unity3d while-loop infinite-loop yield-return