【问题标题】:How to make loop execute one iteration per 2 seconds with yield?如何使用产量使循环每 2 秒执行一次迭代?
【发布时间】:2014-10-21 22:45:40
【问题描述】:

无法理解协程工作的逻辑。在我的示例中,据我了解,循环必须每两秒执行一次迭代,但在启动程序后它会等待两秒钟并执行整个循环。

不明白,怎么了。

    void Start ()
    {
        StartCoroutine ("MyCoroutine");
    }

    IEnumerator MyCoroutine()
    {
        yield return new WaitForSeconds(2.0f);      

        for (int i = 0; i < 5; i++)
        {
            Debug.Log(i); // It must execute ont time per 2 seconds?
            yield return null;
        }
    }

【问题讨论】:

  • 您需要将 yield waitforseconds 放入循环中 - 这是 unity 中断和等待的行

标签: c# unity3d yield coroutine


【解决方案1】:

您应该在循环的每个步骤中等待:

IEnumerator MyCoroutine()
{
    for (int i = 0; i < 5; i++)
    {
        Debug.Log(i); // before waiting
        yield return new WaitForSeconds(2.0f);
        // after waiting
    }
}

【讨论】:

  • 我了解 WaitForSeconds 的工作原理,但我想知道,yield return null; 在循环中需要什么
  • yield return null 等待 1 个游戏帧。因此,如果您将 yield return null 放在循环中,它将每帧执行一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 2018-01-11
  • 2021-06-07
  • 1970-01-01
  • 2013-04-24
相关资源
最近更新 更多