Game Development Reference
In-Depth Information
08 // Use this for initialization
09 void Start ()
10 {
11 //Cache transform
12 ThisTransform = transform;
13 }
14 }
Coroutines
Before proceeding with the power-up PingPong movement, we'll take a detour into the world
of coroutines, which will come in useful for us soon. In Unity, coroutines
act like
threads or
asynchronous functions, if you're familiar with those concepts. In short, typical functions in Unity
and C# act
synchronously
. This means that, when an event (like
Start
) calls a function in a class,
the function performs its behavior sequentially, line by line from top to bottom, and then finally
terminates at the end, returning a value. When the function returns, the calling event will resume
its execution at the next line. But coroutines don't seem to act that way. They act like they are
asynchronous (although they are not truly so). When you call a coroutine, it starts execution and
seems to “run in the background”
at the same time
as other functions. With this ability comes great
power, as we'll see. Consider the following Listing 4-6, which uses a coroutine; comments follow.
Listing 4-6. Sample Coroutine
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
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 }