协程完成后如何继续功能? [英] How to continue the function only after the coroutine completes?

查看:92
本文介绍了协程完成后如何继续功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

输出:

时间1- 0
时间3-0
time2- 3.0146

time1- 0
time3- 0
time2- 3.0146

我想要的输出是:

时间1- 0
时间2-3
时间3-3

time1- 0
time2- 3
time3- 3

推荐答案

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

The documentation at https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html seems to have an example that is almost identical to what you are trying to do:

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)); 强制其等待方法,然后继续.

The key point seems to be that their Start routine returns IEnumerator and then uses yield return StartCoroutine(WaitAndPrint(2.0F)); to force it to wait on that method before continuing.

对您而言,等价于:

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

这篇关于协程完成后如何继续功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆