Coroutine 中的 while(true) 然后把它放在 void Start() 和没有 while(true) 但把它放在 void Update() 之间的区别

Difference between while(true) in Coroutine then put it in the void Start() and not having while(true) but put it in the void Update()

我试图让游戏在每个随机时间段产生敌人,所以我在 Coroutine 中使用 yield return new WaitForSeconds(...),正如标题所说,我可以在 Coroutine 中使用 while(true) 和在 void Start() 中调用协程,生成的东西工作得很好。但是当我删除 while(true) 并在 void Update() 中调用协程时,敌人会毫无延迟地疯狂生成。这是为什么??

因为我猜你不会等待,而是开始一个新的并发例程每一帧所以在开始时延迟过去一次后,你现在每帧都有一个调用!

协程不会延迟启动它的外部代码。

要么使用例如

[SerializeField] private float delay;

private void Start()
{
    StartCoroutine(Routine);
}

private IEnumerator Routine()
{
    while(true)
    {
        yield return new WaitForSeconds(delay);

        DoSomething();
    }
}

或者直接

// If you make Start an IEnumerator then Unity automatically runs it as a Coroutine 
private IEnumerator Start()
{
    while(true)
    {
        yield return new WaitForSeconds(delay);

        DoSomething();
    }
}

或者,如果您想使用 Update,则等效项需要一个计数器,例如

private float timer;

private void Start()
{
    timer = delay;
}

private void Udpate()
{
    timer -= Time.deltaTime;
    if(timer <= 0)
    {
        DoSomething();
        timer = delay;
    }
}

我不会把两者混为一谈 ;)

而且我个人认为协程在大多数情况下更易于阅读和维护。