Game Development Reference
In-Depth Information
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 funcion will coninue from the line ater the
yield
statement the next ime 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 execuion of
the
Update
funcion unil a certain event has occurred, such as
WaitForSeconds
,
WaitForFixedUpdate
,
Coroutine
, and
StartCoroutine
.
You can't use
yield
from within
Update
or
FixedUpdate
,
but you can use
StartCoroutine
to start a funcion that can
use
yield
.
WaitForSeconds
Suspends the
coroutine
execuion for the given amount of seconds.
WaitForSeconds
can only be used with an
yield
statement in
coroutines
.
Example
function Start() {
// Prints 0
Debug.Log (Time.time);
// Waits 5 seconds
yield WaitForSeconds (5);
// Prints 5.0