Game Development Reference
In-Depth Information
Starting Coroutines
There are actually two types of Coroutines (it is best to think of them in that way, even
though they are actually the same thing): those that are just launched ( fire and for-
get ) and those that can be managed. The difference is just in the way they are called. The
fire and forget Coroutine functions are simply called by using the following code:
StartCoroutine(MyCoroutine()); //or
StartCoroutine(MyCoroutine(MyParameter)); //to use
parameters
In the preceding code, the MyCoroutine function is started using the delegate meth-
od. Once started, it will not finish until either the function ends or
StopAllCoroutines() is called. Now, start the Coroutine using the following code:
StartCoroutine("MyCoroutine"); //or
StartCoroutine("MyCoroutine", myParameter); //to use
parameters
In the preceding code, you specify the name of your Coroutine function and the method's
name using a string. This enables you to stop the Coroutine from running anytime (and
from anywhere) using the following code:
StopCoroutine("MyCoroutine");
Note
Currently, there are some enhancements being made in Unity that will enable you to stop
the Coroutines that are called using the method's name. It is not clear yet whether this will
be in the 4.x or 5.x timescales. Keep watching!
The invocation path is something to be kept in mind. You might ask why not just use the
second method all the time. The answer is simple. Unity has to use slower methods to dis-
cover the method it needs to track when you provide the Coroutine's name as a string; just
passing the method's name is quicker and smoother. The best advice would be to use each
type according to its strengths. Only use the string launch method when you need to man-
age a background task and use the method names when it is a short-lived function that is
solely aimed at accomplishing a single task. For everything else, just weigh up the pros
and cons of each approach as you implement it.
Search WWH ::




Custom Search