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 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 the next time it is called. The result would be something similar to the following code.

Example

function Start() {
  while (true) { //Use this line instead of Update()
    //do step 0
    Debug.Log("Do step 0");
    yield;  //wait for one frame
    //do step 1
    Debug.Log("Do step 1");
    yield;  //wait for one frame    
  }
}

The preceding code will have a similar result without having a new variable and an extra if statement to check for each step event.

You can also pass special values to the yield statement to delay the execution of the Update function until a certain event has occurred, such as WaitForSeconds, WaitForFixedUpdate, Coroutine, and StartCoroutine.

Note

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.164.75