团结不喜欢虚空

时间:2014-05-25 17:17:17

标签: c# unity3d void

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

// Use this for initialization
void Start () {
    //Declare intager Hunger
    int Hunger;
        Hunger = 100; 
    GUI.Box(new Rect(10,10,100,90), "Stats");


    GUI.Label (Rect (10,40,100,20), GUI.tooltip,GUIContent("Hunger", Hunger));
}
}

// Update is called once per frame
void Update () {
    //Every ten seconds Hunger goes down by one.
    Hunger = Hunger - 1;
    yield WaitForSeconds = 10;
}
};


};

这是我即将推出的游戏Rust and Wood中的UI代码。它是完美的,但Unity在void Update()中对虚空大喊大叫。请帮忙。

2 个答案:

答案 0 :(得分:2)

您不能在Update()方法中使用yield,因为它是每帧执行的。 通过用IEnumerator替换void,只能将Start()方法声明为coroutine。

试试这个。

public class HungerClass : MonoBehaviour {

    int Hunger = 100;

    IEnumerator Start () 
    {
        while (true)
        {
            //Every ten seconds Hunger goes down by one.
            Hunger = Hunger - 1;
            yield return  new WaitForSeconds(10);   
        }
    }

    void OnGUI()
    {
        GUI.Label(new Rect (10,40,100,20), "Hunger = " + Hunger);
    }
}

答案 1 :(得分:1)

问题不在void声明中。

}方法还有Start};,文件末尾int Hunger;

同样Start应该在void方法之外。

修改 我注意到你正在尝试使用Coroutines错误。将IEnumerator替换为WaitForSeconds并使用正确的Update协程。另外@JeanLuc表示Start方法不能用作协程。只有using UnityEngine; using System.Collections; public class NewBehaviourScript : MonoBehaviour { int Hunger; void Start () { Hunger = 100; GUI.Box(new Rect(10,10,100,90), "Stats"); GUI.Label (Rect (10,40,100,20), GUI.tooltip,GUIContent("Hunger", Hunger)); StartCoroutine(TickHunger()); } IEnumerator TickHunger () { while(Hunger > 0) { //Every ten seconds Hunger goes down by one. Hunger = Hunger - 1; yield return new WaitForSeconds(10); } } }; 方法。所以你也需要改变它。

所以它应该是:

{{1}}