Unity:更新中的 Wait() 几乎可以正常工作(但不完全是)

Unity: Wait() in Update almost working (But not quite)

我有一个带有更新功能的代码 (C#),有时需要等待几秒钟。问题是,当它执行等待命令时,它继续执行更新功能,导致本应延迟的位被完全跳过。 由于布尔变量,更新只会执行一次,直到我再次使其可用,所以这没问题。 该代码无需整个等待即可运行,所以不用担心,我省略了大部分与等待无关的行。

void Update()
{

    if (RoundOver == false)
    {
        RoundOver = true;
        Seconds = 3;
        Debug.Log("Waiting", gameObject);
        StartCoroutine(Wait());
        if (Continue)
        {
            Continue = false;
            Debug.Log("Done Waiting", gameObject);
            RoundNumber += 1;                //Just game stuff
            ZombiesLeft = ZombieAmount();    //Just game stuff
            RoundOver = false;
        }
        Debug.Log("Done wit stuff", gameObject);
    }
    if (counter > DelayTime && RoundOver == false)
    {
        counter = 0;
        Debug.Log("Going to spawn a zombie", gameObject);
        SpawnZombie();
    }
    counter += Time.deltaTime;
    }

具有 les 等待功能:

IEnumerator Wait()
{
    Debug.Log("ACTUALLY WAITING", gameObject);
    yield return new WaitForSeconds(Seconds);
    Continue = true;
    Debug.Log("ACTUALLY WAITING DONE", gameObject);
}

输出结果如下:

Waiting
ACTUALLY WAITING
Done wit stuff
ACTUALLY WAITING DONE

显然正确的顺序应该是

Waiting
ACTUALLY WAITING
ACTUALLY WAITING DONE
Done wit stuff

编辑: if (continue) 中的块应该在满足(此处隐藏的)要求时激活第二个块。第二个块将继续做它的事情直到它完成(可能需要几分钟)然后通过将 RoundOver 设置为 false 再次重新启用第一个块。第一个块本质上是继续重新运行第二个块,增加变量,如 RoundNumber +=1,并且,这是这里唯一的问题,让第二个块间隔 3 秒。

您的调试语句 Debug.Log("Done wit stuff", gameObject); 在 if 语句 if (Continue) 之外。正因如此,即使协程还是运行.

也会显示

您不能在 Update 函数中等待,您只能在 returns 和 IEnumerator.

的函数中等待

为此你可以做这样的事情

void Update()
{
   if (RoundOver == false)
   {
        RoundOver = true;
        StartCoroutine(Wait());
   }
   if (counter > DelayTime && RoundOver == false)
   {
    counter = 0;
    Debug.Log("Going to spawn a zombie", gameObject);
    SpawnZombie();
   }
   counter += Time.deltaTime;
}

IEnumerator Wait()
{
    Seconds = 3;
    Debug.Log("Waiting", gameObject);
    Debug.Log("ACTUALLY WAITING", gameObject);
    yield return new WaitForSeconds(Seconds);
    Debug.Log("Done Waiting", gameObject);
    RoundNumber += 1;                //Just game stuff
    ZombiesLeft = ZombieAmount();    //Just game stuff
    RoundOver = false;
    Debug.Log("ACTUALLY WAITING DONE", gameObject);
    Debug.Log("Done wit stuff", gameObject);
}

虽然这不是最干净的东西,但如果可能的话,我会从 Update 中删除所有代码,并在需要时启动协程。

我通过将 void SpawnZombie() 变成一个 IEnumerator 而不是单独的 Wait() 来解决这个问题。然后我将 SpawnZombie() 替换为 StartCoroutine(SpawnZombie())。为了让它像我想要的那样,我在 SpawnZombie() 中添加了一个 if 以确保只在我想要的时候等待 3 秒。