Game Development Reference
In-Depth Information
Appendix B
Coroutines and Yield
This appendix presents a brief review of
coroutines
and
yield
, referenced from the Unity
Scriping Reference.
YieldInstruction
When wriing game code, one oten ends up needing to script a sequence of events. This
could result in a code similar to the following.
Example
private var state = 0;
function Update() {
if (state == 0) {
// do step 0
Debug.Log("Do step 0");
state = 1;
return;
}
if (state == 1) {
// do step 1
Debug.Log("Do step 1");
state = 0;
return;
}
}
The preceding code basically does
step0
and
step1
, then goes back to
step 0
(as a loop),
and then if there are more events that will happen after
step1
, and so on. Too many
if
statements can make the code look ugly in the long run.