协程完成后如何继续功能?

时间:2019-02-06 17:08:48

标签: c# visual-studio unity3d coroutine

void Generate()
{
    StartCoroutine(FallDelayCoroutine());
    print("time3- " + Time.time);
}

IEnumerator FallDelayCoroutine()
{     
    print("time1- "+ Time.time);
    yield return new WaitForSeconds(3f);
    print("time2- " + Time.time);
}

输出:

  

time1- 0
  时间3-0
  time2- 3.0146

我想要的输出是:

  

time1- 0
  时间2-3
  时间3-3

2 个答案:

答案 0 :(得分:1)

https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html上的文档似乎有一个示例,与您尝试执行的操作几乎相同:

IEnumerator Start()
{
    // - After 0 seconds, prints "Starting 0.0"
    // - After 2 seconds, prints "WaitAndPrint 2.0"
    // - After 2 seconds, prints "Done 2.0"
    print("Starting " + Time.time);

    // Start function WaitAndPrint as a coroutine. And wait until it is completed.
    // the same as yield WaitAndPrint(2.0);
    yield return StartCoroutine(WaitAndPrint(2.0F));
    print("Done " + Time.time);
}

// suspend execution for waitTime seconds
IEnumerator WaitAndPrint(float waitTime)
{
    yield return new WaitForSeconds(waitTime);
    print("WaitAndPrint " + Time.time);
}

关键点似乎是他们的Start例程返回IEnumerator,然后使用yield return StartCoroutine(WaitAndPrint(2.0F));强制其在继续该方法之前等待。

对您而言,等价于:

IEnumerator Generate()
{
    yield return StartCoroutine(FallDelayCoroutine());
    print("time3- " + Time.time);
}

答案 1 :(得分:0)

作为使用两个协程的other answer的替代方案,您还可以添加一个回调,例如

IEnumerator FallDelayCoroutine(Action whenDone)
{     
    print("time1- "+ Time.time);
    yield return new WaitForSeconds(3f);
    print("time2- " + Time.time);

    whenDone?.Invoke();
}

并使用例如一个lambda表达式

void Generate()
{
    StartCoroutine(FallDelayCoroutine(() => {
        print("time3- " + Time.time);
    }));  
}

或带有方法

void Generate()
{
    StartCoroutine(FallDelayCoroutine(OnFallDelayDone));  
}

private void OnFallDelayDone()
{
    print("time3- " + Time.time);
}