How to continue the function only after the coroutine completes?

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

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


        
相关标签:
2条回答
  • 2021-01-27 17:15

    As alternative to the other answer using two Coroutines you could also add a callback like e.g.

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

    and call it either using e.g. a lambda expression

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

    or with a method

    void Generate()
    {
        StartCoroutine(FallDelayCoroutine(OnFallDelayDone));  
    }
    
    private void OnFallDelayDone()
    {
        print("time3- " + Time.time);
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题