O'Reilly logo

Unity 3 Game Development HOTSHOT by Jate Wittayabundit

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix B. Coroutines and Yield

This appendix presents a brief review of coroutines and yield, referenced from the Unity Scripting Reference.

YieldInstruction

When writing game code, one often 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.

In this case, it's more convenient ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required