- Home /
What will StopCoroutine exactly do?
I was wondering if you call StopCoroutine, whether the coroutine stops instantly or will the coroutine break on the next yield.
It's really important to know if it's possible for the coroutine to still execute commands after the Stop has been called.
Any help please? Thanks in advance.
Answer by Bunny83 · Aug 27, 2012 at 10:15 AM
You can't even call stop in between yield because everything is running in the same thread. Whereever you want to call stop, it will happen when the coroutine has reached the next yield. Even when Unity would support threads, you can only terminate a coroutine when it reaches the next yield.
So the short answer is: No, the coroutine can't execute any code when StopCoroutine is called. That's because the coroutine has to finish the current step before any other code can be executed.
One exception: When you call StopCoroutine inside the coroutine itself, it will of course finish the current step. If you want to break out of a coroutine, use yield break;
Answer by MadDave · Aug 27, 2012 at 10:25 AM
Coroutines are not threads. They do not run parallel to your other functions. CoRoutines are simply called at some point in the game loop, on the main thread. StopCoroutine simply removes the Coroutine from the scheduling list. It will not be called again.
In other words: Yes, you can be sure that the CoRoutine will not run again after a call to StopCoRoutine. But technically speaking it is not "stopped instantly" because it is actually not executing at this point. That implies that it always stops at a yield - that is the only point where it is ever interrupted. If you are in a different function, your CoRoutine is currently waiting at a yield.
Hope that makes it clear :)