【问题标题】:Coroutines Unity协程统一
【发布时间】:2014-10-29 13:45:12
【问题描述】:

我想了解 c# 中协程的语法(因为它对我来说真的很不寻常......)。

当我们做这样的事情时:

yield return new WaitForSeconds(2.0f);

Firstable:我明白这句话的目的,但不明白语法。

WaitForSeconds 类代表什么?它应该是 IEnumerator 类型,因为这是函数的返回类型。但是根据文档http://docs.unity3d.com/ScriptReference/WaitForSeconds-ctor.html,它没有返回类型,它是一个 Yield 指令(在那里很困惑)

那么在这种情况下,yield 的目的是什么?

为什么我们要把它和 return 关键字混在一起呢?

提前致谢。

【问题讨论】:

  • 正在写一个答案,但基本上它应该是该站点的复制粘贴:twistedoakstudios.com/blog/… 我假设您知道协程的作用以及它为什么有用,否则该链接将无用.
  • 你应该刚刚添加它作为答案;)

标签: unity3d coroutine


【解决方案1】:
    void Start()
    {
       //to start a routine
       StartCoroutine(A_routine());

       //this is same as above
       IEnumerator  refer_to_A_routine = A_routine();
       StartCoroutine(refer_to_A_routine);

    }

    IEnumerator A_routine()
    {
         //waits for 0.1 second
         yield return new WaitForSeconds(0.1f)

         //waits till another_routine() is finished
         yield return StartCoroutine(another_routine())

           //starts another_routine() there is no wait
           StartCoroutine(another_routine())
    }

【讨论】:

    【解决方案2】:

    它只是允许您并行执行一些代码。

    例如:

    IEnumerator PrintAfterDelay()
    {
        yield return new WaitForSeconds(5.0f);
    
        //Rest of the code in this method will execute after 5 seconds while all
    all other code will be execute in parallel
        Debug.Log("Now I am here after 5 Seconds");
    }
    

    例如在 Start() 中调用它。

    void Start()
    {
        StartCoroutine("PrintAfterDelay");
        Debug.Log("I am here");
    }
    

    【讨论】:

      【解决方案3】:

      使用 yield return 调用创建一个正在返回的类型的 IEnumerable。这允许调用函数在计算它们时处理一个值列表,而不是在最后一次处理所有值,就像您刚刚返回一个集合一样。

      在 Unity3d 中这很重要,因为绘制周期基本上都发生在单个线程上,因此您可以使用协程和 yield return 语法在脚本中嵌套行为。

      新的 WaitForSeconds(...) 调用允许执行上下文在一段时间内返回到外部调用者,同时有效地暂停执行该 MonoBehaviour 的空操作,而不会暂停整个绘制线程。

      【讨论】:

        猜你喜欢
        • 2022-08-03
        • 2019-03-28
        • 1970-01-01
        • 2019-06-26
        • 1970-01-01
        • 2020-06-13
        • 1970-01-01
        • 2019-08-04
        • 1970-01-01
        相关资源
        最近更新 更多