- Home /
StartCoroutine?
Can anyone explain me about Coroutine. I am not able to understand in docs.unity3d.com.
There is an article on coroutines here: http://unitygems.com/coroutines/ if you want to read about it.
Answer by aldonaletto · Dec 02, 2012 at 05:04 PM
When you start a coroutine, it's executed until an yield instruction is found. If it's an "empty yield" (returns nothing in JS, or returns null in C#), the coroutine is suspended and control returns to the calling code, as if the coroutine has finished - but it's still alive and kicking! Next frame, the coroutine will wake up automatically in the instruction following the yield, and this will be repeated until the coroutine reaches its last instruction, when it dies silently.
yield; // "empty yield" in JS
yield return null; // "empty yield" in C#
When you yield to another coroutine, on the other hand, control is passed to this coroutine, and the calling coroutine gets suspended at that yield until the called coroutine finishes:
yield AnotherCoroutine(); // yielding to AnotherCoroutine in JS
yield return StartCoroutine(AnotherCoroutine()); // the same in C#
Each coroutine you start allocates an object in the heap, and will be there until its end is reached. Care must be taken when starting a coroutine in periodic functions like Update, LateUpdate, FixedUpdate etc. because you can crowd the memory with thousands of coroutines executing in parallel - the frame rate drops like a rock, and Unity may even crash when enough coroutines are stealing CPU time and memory. Usually a boolean flag is used to avoid such disasters: you start the coroutine only when the flag is false, set it at the coroutine beginning and clear it at the end, like this:
var executing = false;
function Update(){
if (executing == false){
StartCoroutine(ACoroutine());
print("Coroutine started");
}
}
function ACoroutine(): IEnumerator {
executing = true; // set the flag
yield WaitForSeconds(10.0);
print("Coroutine ended");
executing = false; // clear the flag before returning
}
This code prints "Coroutine started" at first, and 10 seconds after "Coroutine ended" magically appears in the console, then Update will print "Coroutine started" again, and so on.
If you want an example of how to use a coroutine, take a look at this question, for instance.
Answer by nventimiglia · Dec 02, 2012 at 06:11 PM
IEnumerator MyCoroutine()
{
// wait ONE FRAME and continue
yield return null; // SIC - that's null, not "1" or "frame" or anything else
// wait 5 seconds and continue
yield return new WaitForSeconds(5);
// Custom Update Routine which repeats forever
do
{
// wait one frame and continue
yield return 1;
if (IWantToEndEarly)
{
// end
yield break;
}
} while (true);
// end naturally
}
The 1 in "yield return 1" doesn't mean it waits one frame. You should use "yield return null" ins$$anonymous$$d.