Game Development Reference
In-Depth Information
StartCoroutine
StartCoroutine
starts a
coroutine
.
The execution of
coroutine
can be paused at any point using the
yield
statement. The
yield return
value specifies when
coroutine
is resumed.
Coroutines
are excel-
lent when modeling behavior over several frames.
Coroutines
have virtually no per-
formance overhead. The
StartCoroutine()
function always returns a value immedi-
ately; therefore, you can yield the result. This will wait until
coroutine
has finished exe-
cution.
Tip
When using JavaScript, it is not necessary to use
StartCoroutine
; the compiler will
do this for you. However, when writing C# code, you must call
StartCoroutine
. (For
more details, refer to
Appendix C
,
Major Differences Between C# and Unity JavaScript
.)
In the following example, we will show how to invoke a
coroutine
and continue ex-
ecuting the function in parallel:
// JavaScript user:
function Start() {
// Starting = 0.0
Debug.Log ("Starting = " + Time.time);
// StartCoroutine WaitAndPrint (In JavaScript, you can
also useWaitAndPrint(5.0) which will get the same result.
StartCoroutine(WaitAndPrint(5.0));
// Before WaitAndPrint = 5.0
Debug.Log ("Before WaitAndPrint = " + Time.time);
}
function WaitAndPrint(waitTime : float) {
//Suspend execution for 5 seconds
yield WaitForSeconds(waitTime);
// WaitAndPrint = 5.0
Debug.Log ("WaitAndPrint = " + Time.time);
}