Game Development Reference
In-Depth Information
Before reading the following comments, execute this code in Unity and look inside the Console
window to see what happens. The result is shown in Figure
4-7
.
Figure 4-7.
Using coroutines. Notice that the string “Counter Finished”, which occurs inside Start on a line after the function
Counter is called, is actually printed before the counter function completes!
Lines 07 and 18.
Both of these lines declare a coroutine. Notice that many
Unity events, like
Start
, can be declared as a coroutine. They need not always
return
void
. Coroutines are always declared with an
IEnumerator
return type,
and they always feature a
yield
statement somewhere in their body. Technically,
a function that returns a type of
IEnumerator
and has a
yield
statement in its
body is a coroutine. So in Listing 4-6, both
Start
and
Counter
are coroutines.
Line 10.
In this class, the
Start
coroutine is invoked automatically by Unity, just
as it invokes the normal
Start
event, but line 10 invokes a coroutine manually.
Notice that a coroutine cannot be called like a regular function. Instead, the
function
StartCoroutine
must be used to initiate the specified coroutine. If
you've actually tested and run this code, you'll see from the output in the
Console window, and from Figure
4-7
, that the
Counter
coroutine is executed,
but
Start
does not
wait for it to finish before resuming execution on the next line
at line 13. Line 13 is executed, and “Counter Finished” is printed to the console
before
the
Counter
coroutine is completed entirely. This demonstrates the
asynchronous behavior of coroutines.