Hold or Wait while Coroutine finishes

早过忘川 提交于 2019-12-11 12:46:43

问题



In the example below, how can I get FinishFirst() to complete first before running DoLast(), while still retaining the 'public void StartPage()' signature?


I'm trying to avoid making "StartPage()" return an IEnumerator as that would force me to change it in the interface. It would be great if my Interface for StartPage() supported both IEnumerator and Void without needing to implement both.

public void StartPage()
{
    print("in StartPage()");
    StartCoroutine(FinishFirst(5.0f));
    DoLast();
    print("done");

}    

IEnumerator FinishFirst(float waitTime)
{
    print("in FinishFirst");        
    yield return WaitForSeconds(waitTime);
    print("leave FinishFirst");
}    

void DoLast()
{
    print("do after everything is finished");
}

回答1:


Use of a lock-object should work:

object lockObject = new object();

public void StartPage()
{
    print("in StartPage()");
    StartCoroutine(FinishFirst(5.0f));
    DoLast();
    print("done");

}    

IEnumerator FinishFirst(float waitTime)
{
    lock(lockObject)
    {
        print("in FinishFirst");        
        yield return WaitForSeconds(waitTime);
        print("leave FinishFirst");
    }
}    

void DoLast()
{
    lock(lockObject)
    {
        print("do after everything is finished");
    }
}



回答2:


I know this is an old question, but if I understand the question correctly, something like this works. DoLast() will run at the end of the co-routine.

IEnumerator FinishFirst(float waitTime)
{
    print("in FinishFirst");        
    yield return WaitForSeconds(waitTime);
    print("leave FinishFirst");
    DoLast();
}  

I use a lot of similar code inside co-routines to clean and kill the routine if another one was created when this one is running (mainly for typed-text dialog boxes where the text might change at any time).



来源:https://stackoverflow.com/questions/9731295/hold-or-wait-while-coroutine-finishes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!