Game Development Reference
In-Depth Information
Line 15.
In the world of coroutines,
yield break
is equivalent to
return null
in the world of functions. In other words,
yield break
terminates the coroutine
at that line, and any subsequent lines (if there are any) will not be executed.
There's also another kind of
yield
statement, which is
yield return null
.
This
terminates execution of the coroutine for the current frame, but the coroutine will
resume at the
next line
on the
next frame
. We'll see this form of
yield
in action
shortly when creating the bobbing motion for our Cash Power-Up object.
Line 23.
This
yield WaitForSeconds
statement works like a
Sleep
function. In
Listing 4-6,
yield WaitForSeconds
is used to suspend execution of the coroutine
for 1 second before resuming on the next line. Since this statement is called
inside a
For
loop, it executes once on each iteration.
There's another and interesting use of
yield
, however, which is not so widely documented. You may
be wondering how we could fix the “asynchronous problem” in Listing 4-6 so that line 13 was truly
executed
after
the
Counter
coroutine had completed entirely, and not sooner. To do that, consider
the revised code, as shown in Listing 4-7.
Listing 4-7. Waiting for a Coroutine to Complete
01 using UnityEngine;
02 using System.Collections;
03
04 public class PrintHelloWorld : MonoBehaviour
05 {
06 // Use this for initialization
07 IEnumerator Start ()
08 {
09 //Start Coroutine
10
yield return StartCoroutine(Counter());
11
12 //Has finished
13 Debug.Log ("Counter Finished");
14
15 yield break;
16 }
17
18 IEnumerator Counter()
19 {
20 for(int i=0; i<10; i++)
21 {
22 Debug.Log (i.ToString() + "Seconds have elapsed");
23 yield return new WaitForSeconds(1.0f);
24 }
25 }
26 }
In short, the
yield
statement can be used inside a coroutine (such as
Start
) to wait for the
termination of another coroutine (such as
Counter
). With this code, line 13 will not be executed until
the
Counter
coroutine has ended. Before moving on, I recommend playing around with coroutines.
They are powerful and we'll put them to good use in the next section to create an endless PingPong
motion for power-ups.