你好我一直在使用Coroutine功能遇到麻烦并等待几秒钟。单击按钮后,我的代码应该:
但我得到的是:
我如何才能获得它,以便等待能够正确地停止正常运行的代码。
IEnumerator wait(){ // This is the function to call it to wait
Debug.Log ("Before Wait");
yield return new WaitForSeconds (2);
Debug.Log ("After Wait");
}
void Update () {
if (chosen == false) {
if (choice != "")
chosen = true;
}
if (chosen == true){
enemyChoice = "";
int n = rnd.Next(num.Count);
enemyChoice = choices [n];
Debug.Log (choice); // Here choice should be printed, then the coroutine started and then enemy choice printed
StartCoroutine (wait ());
Debug.Log (enemyChoice);
chosen = false;
toDecide = true;
}
if (toDecide == true){ // sorry for the clunky way of deciding the result
if (choice == enemyChoice) {
Debug.Log ("Draw");
} else if (choice == "rock" && enemyChoice == "paper") {
Debug.Log ("Lose");
} else if (choice == "rock" && enemyChoice == "scissors") {
Debug.Log ("Win");
} else if (choice == "paper" && enemyChoice == "rock") {
Debug.Log ("Win");
} else if (choice == "paper" && enemyChoice == "scissors") {
Debug.Log ("Lose");
} else if (choice == "scissors" && enemyChoice == "paper") {
Debug.Log ("Win");
} else if (choice == "scissors" && enemyChoice == "rock") {
Debug.Log ("Lose");
} else {
Debug.Log ("Error");
}
toDecide = false;
choice = "";
enemyChoice = "";
}
}
答案 0 :(得分:2)
首先,您必须了解Update
是每帧调用的方法。一次又一次。
如果您的游戏达到每秒60帧,这意味着Update
每秒会被调用60次(您可以在Debug.Log("Update!");
中检查此添加Update()
)。
现在,如果你想要一些等待x秒的逻辑,它应该在Update
之外,因为我们知道Update
会一次又一次地被调用,而不关心任何WaitForSeconds
// Use this for initialization
void Start()
{
Method1();
StartCoroutine(Method2CR());
}
// Update is called once per frame
void Update() {
// I don't want call my methods/Coroutines many times per frame..
}
IEnumerator Wait5Seconds()
{
yield return new WaitForSeconds(5f);
}
void Method1()
{
Debug.Log("Method1 before Wait5Seconds: " + Time.time);
StartCoroutine(Wait5Seconds());
Debug.Log("Method1 after Wait5Seconds: "+ Time.time);
}
IEnumerator Method2CR()
{
Debug.Log("Method2CR before Wait5Seconds: "+ Time.time);
yield return StartCoroutine(Wait5Seconds());
Debug.Log("Method2CR after Wait5Seconds: " + Time.time);
}
1}}。
这是两个方法的简单示例(好吧,一个是方法,另一个是协程)和执行结果:
Method1 before Wait5Seconds: 0
Method1 after Wait5Seconds: 0
Method2CR before Wait5Seconds: 0
Method2CR after Wait5Seconds: 5.010797
,输出为:
Script Lifecycle Flowchart
您可以阅读this以了解Monobehaviour元素幕后发生的事情。查看date(bySettingHour:minute:second:of:options:)
图片。
答案 1 :(得分:1)
以前曾多次在StackOverflow和Unity Answers上提出类似的问题。
协同程序不会暂停执行它们被调用的函数。你必须将你的逻辑放在一个大的协程中:
1: a
b
patA matches