问题
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