Overview: Coroutines & Yield Manual     Reference     Scripting  
Scripting
Overview: Coroutines & Yield

When writing game code, one often ends up needing to script a sequence of events. This could result in code like the following.

JavaScript
private var state = 0;

function Update() {
if (state == 0) {
// do step 0
state = 1;
return;
}
if (state == 1) {
// do step 1
state = 2;
return;
}
// ...
}

It is often more convenient to use the yield statement. The yield statement is a special kind of return, that ensures that the function will continue from the line after the yield statement next time it is called.

JavaScript
while(true) {
// do step 0
yield; // wait for one frame
// do step 1
yield; // wait for one frame
// ...
}

You can also pass special values to the yield statement to delay the execution of the Update function until a certain event has occurred.

JavaScript
// do something
yield WaitForSeconds(5.0); // wait for 5 seconds
// do something more...

You can both stack and chain coroutines.

This example will execute Do but continue after calling do immediately.

JavaScript
Do ();
print ("This is printed immediately");

function Do () {
print("Do now");

yield WaitForSeconds (2);

print("Do 2 seconds later");
}

This example will execute Do and wait until it is finished before continuing its own execution

JavaScript
// chain the coroutine

yield StartCoroutine("Do");
print("Also after 2 seconds");

print ("This is after the Do coroutine has finished execution");

function Do () {
print("Do now");

yield WaitForSeconds (2);

print("Do 2 seconds later");
}

Any event handler can also be a coroutine.

Note that you can't use yield from within Update or FixedUpdate, but you can use StartCoroutine to start a function that can.

See YieldInstruction, WaitForSeconds, WaitForFixedUpdate, Coroutine and MonoBehaviour.StartCoroutine for more information on using yield.