- Home /
How to wait for Coroutine to finish?
I would like to call a coroutine function and return a value. To do so, I am calling function StartCheck() which calls a StartCoroutine(WaitStartCheck()). Below is a sample code to explain better what I'm trying to do:
private bool checkComplete = false;
private bool check = false;
bool StartCheck() {
checkComplete = false;
check = false;
StartCoroutine(WaitStartCheck());
while (!checkComplete) {
//some code
print(Time.deltaTime);
}
return check;
}
IEnumerator WaitSStartCheck() {
yield return new WaitForSeconds(5.0f);
if (condition)
check = true;
else
check = false;
checkComplete = true;
}
The problem is that the while loop is freezing Unity. How can I make this to work?
Thank you!
Answer by fafase · Jan 18, 2015 at 11:02 AM
Why would you use boolean when you can get the program to wait for the coroutine without stopping:
bool check;
IEnumerator Somewhere()
{
yield return StartCoroutine(WaitSStartCheck());
if(check){}
}
IEnumerator WaitSStartCheck() {
yield return new WaitForSeconds(5.0f);
check = condition;
}
Thanks fafase for your reply. I have tried a lot of ways to make this work. I did try the way you're showing here, but the problem with this is that you can not call the function Somewhere() to return the boolean value right? I want Somewhere() to return check variable's value.
Why do you need it to return bool? Since check is global to the class you get your result. You should tell more about the flow of your program.
Nonetheless, if you need a coroutine to "return" a value then you can pass a reference type like a class:
class Data{public bool check;}
IEnumerator Somewhere()
{
Data data = new Data()
yield return StartCoroutine(WaitSStartCheck(data));
if(data.check){}
}
IEnumerator WaitSStartCheck(Data data) {
yield return new WaitForSeconds(5.0f);
data.check = condition;
}
Then it kinda looks like it returns something.
@fafase, Your answer didn't do what i needed, but it helped me in some other way... Thankyou! :)
Answer by sbethge · Sep 20, 2019 at 07:53 PM
Check out Run.Coroutine of CoroutineHelpers. It returns a Run object which has an isDone property.
Your answer
Follow this Question
Related Questions
Stop Current Coroutine, Then Restart It 1 Answer
Yield position within while loop in coroutine 1 Answer
StopCoroutine() is not stopping my coroutines 1 Answer
Problem with while loop in Coroutine 2 Answers
Breaking from a Loop 2 Answers