有人能向我解释一下这些协同线之间的区别吗?因为我每次都要调用函数,所以它们不是在做同样的事情吗?
IEnumerator MyRoutine()
{
yield return null;
Debug.Log("Hello");
}
IEnumerator MyRoutine2()
{
while (true)
{
yield return null;
Debug.Log("Hello");
}
}为什么第一次只运行一次,第二次永远运行?
发布于 2022-01-03 17:15:01
当多次调用Coroutines时,它们非常重要。在第一次调用时,它们将从{部件开始执行。它将一直运行到关键字yield return get(s)被执行为止。现在,当同样的协同线再次被调用时,代码将从上次执行的yield return中继续--下一行/语句将被调用。
查看第一个示例(语句),在第一次调用时,Coroutine将返回null。在第二次调用时,它将命中Debug.Log("Hello")并以}结束。
与第二个示例(语句)相比,这里有while(true) { }循环。对于第一次运行,这些部分将被执行:
{
while (true)
{
yield return null; // ends here这和以前差不多。但在第二次执行时,行为将发生变化。它将再次运行Debug.Log("Hello"),但是它会到达while(true) { }循环的末尾,它检查它的条件(它是true),然后再次返回到语句yield return null,在那里它结束。
发布于 2022-01-03 17:18:50
为什么第一个只运行一次,第二个永远运行?
因为第一个在单个yield return之后退出,第二个在无限循环中运行yield return。
在这个构造中,MyRoutine返回一个IEnumerator,但是它的代码在有人枚举IEnumerator之前实际上不会运行。
IEnumerator enum = MyRoutine(); //no code in MyRoutine runs yet
if (enum.MoveNext()) //this actually runs MyRoutine up through the first `yield return`
{
var value = enum.Current;
}
//the next call to enum.MoveNext() continues running MyRoutine _after_ the first `yield return`
var hasRows = enum.MoveNext(); //returns false as Debug.Log("Hello") runs and then MyRoutine exitshttps://stackoverflow.com/questions/70569153
复制相似问题