试图理解协同程序——没有得到预期的输出

Trying to understand coroutines - not getting expected output

这是我尝试使用协程的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {

    void Update(){
        StartCoroutine (Test());
        print ("in update");
    }

    IEnumerator Test()
    {
        for(int i=0;i<1000;i++)
        {
            print(i);
            yield return null;
        }
    }
}

我只是想检查一下普通函数在更新和使用协程中的行为方式之间的区别。我读过协同程序会保留其局部变量的值。但是我得到了奇怪的输出。

See the image for output

您每次 Update() 调用都会启动一个新协程。结果,越来越多的 Test() 实例将并行 运行,并且它们都将在迭代中处于不同的点 - 这就是为什么您的日志每次都填充不同的数字帧(0、0 1、0 1 2、0 1 2 3 等)

您应该做的是从 Start() 方法而不是 Update() 方法启动协程,因此它只启动一次:

void Start(){
    StartCoroutine (Test());
}

void Update(){
    print ("in update");
}

希望对您有所帮助!如果您有任何问题,请告诉我。