- Home /
Does a coroutine end itself automatically?
Hello guys, I have a simple question: does a coroutine terminate itself once it reaches the end of its code block?
I know I know... this is probably a very stupid question, but I just wanna make sure Unity doesn't secretly stack them somehow by using StartCoroutine() and keep them somewhere even though they aren't doing anything anymore.
I know that if I put an infinite while loop in a coroutine, the coroutine will never stop until you tell it to do so (via StopCoroutine(), StopAllCoroutines() or a boolean set in the while loop).
But even then, would it really end? Take a look at this simple example:
IEnumerator TestCoroutine()
{
yield return new WaitForSeconds(0.75f);
DoSomethingHere();
yield return new WaitForSeconds(3f);
DoSomethingElseHere();
yield break; //Is this even needed?
}
Would this coroutine end itself once it reaches the last line, since it is not in an infinite while or for loop? Because if yes, calling it several times (like 4 or 5 times every here and there) wouldn't affect performance overhead at all... right?
I'm just not sure about the usage of these coroutines, maybe it's just me but I have the weird feeling that if I start several of these coroutines over a timespan of many hours of gameplay they never terminate themselves (even though they "should") and get stacked somewhere where they shouldn't, and therefore make the performance suffer a lot.
Thanks in advance for your help,
-Raphael
Answer by Andres-Fernandez · Apr 28, 2014 at 01:50 PM
Yes, they do finish when their block of code ends (or when they find a return or a yield break), no need to worry. They are just like regular functions that are executed at the end of the frame (after the updates) and have the ability of stopping their execution by the use of the yield instruction. Besides that, pretty much like regular functions.
Thanks a lot for the clear and crisp answer! I really appreciate it :)
Answer by HarshadK · Apr 28, 2014 at 01:55 PM
Yes, Co-routine ends itself automatically after it is completed. In the end they are just the functions.
For additional information, the memory management related to the Co-routines this article C# Memory Management for Unity Developers states that:
If you launch a coroutine via StartCoroutine(), you implicitly allocate both an instance of Unity's Coroutine class (21 Bytes on my system) and an Enumerator (16 Bytes). Importantly, no allocation occurs when the coroutine yield's or resumes, so all you have to do to avoid a memory leak is to limit calls to StartCoroutine() while the game is running.