How to continue the function only after the coroutine completes?

前端 未结 2 1898
我寻月下人不归
我寻月下人不归 2021-01-27 16:24
void Generate()
{
    StartCoroutine(FallDelayCoroutine());
    print(\"time3- \" + Time.time);
}

IEnumerator FallDelayCoroutine()
{     
    print(\"time1- \"+ Time.ti         


        
2条回答
  •  春和景丽
    2021-01-27 17:23

    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);
    }
    

    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.

    So the equivalent for you would be:

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

提交回复
热议问题