- Home /
Does a coroutine invoked using StartCorutine() need to finish before code below executes in a function?
I'm not sure how exactly coroutines execute when called in a method, but I'm hoping someone can clear up my understanding here. Using some pseudo code:
void test(){
print("1");
StartCoroutine(PrintTwo());
print("3");
}
IEnumerator PrintTwo(){
yield return new waitForSeconds(5);
print("2");
}
will this code print "1 2 3" or "1 3 2"? To get more at what I'm asking is, does the function wait for the Coroutine to finish before continuing execution, or does it run both at the same time where the outcome would be the latter?
EDIT: After quickly testing it, the outcome was "1 3 2". That being said, is there a way I can require the function to wait until printTwo() has finished before continuing execution? or would this require test to be an IEnumerator itself?
"A coroutine is like a function that has the ability to pause execution and return control to Unity but then to continue where it left off on the following frame." - https://docs.unity3d.com/$$anonymous$$anual/Coroutines.html
You could do a separate coroutine, depending on what it is you're trying to achieve, or simply call the print statement after print("2")
void test(){
print("1");
StartCoroutine(PrintTwo());
}
IEnumerator PrintTwo(){
yield return new waitForSeconds(5);
print("2");
print("3"); // move this here
}
Answer by bobisgod234 · May 15, 2017 at 02:27 AM
is there a way I can require the function to wait until printTwo() has finished before continuing execution? or would this require test to be an IEnumerator itself?
You can yield the result of StartCoroutine, and Unity will not continue past until that coroutine is finished. This will require 'test' to be an IEnumerator itself (and started as a coroutine elsewhere)
IEnumerator test(){
print("1");
yield return StartCoroutine(PrintTwo());
print("3");
}
IEnumerator PrintTwo(){
yield return new waitForSeconds(5);
print("2");
}
should output 1 2 3
Your answer
![](https://koobas.hobune.stream/wayback/20220612122024im_/https://answers.unity.com/themes/thub/images/avi.jpg)