Game Development Reference
In-Depth Information
IEnumerator
At their core, Coroutines are just normal methods, but they are implemented using a par-
ticular generic interface named IEnumerator as their return type. This enables Unity to
track the method's state through several iterations (runs).
Tip
Don't confuse IEnumerator with IEnumerable when defining your Coroutines; oth-
erwise, you will find that they won't work.
To create a basic Coroutine, you simply need to set up the method as shown in the follow-
ing code:
IEnumerator MyCoroutine()
{
//Do something
//Then return
yield return null;
}
This would create a simple single-use Coroutine that would perform a single function, and
when it's finished, it will die and go away.
A more common pattern is to have a loop of some kind within the function that will not
finish until some condition is met; this is done by either using a while or for loop as
follows:
IEnumerator MyCoroutine (){
bool complete = false;
while (!complete)
{
//Do some repetitive task
//When done set complete to true
//Then return control after each step
yield return null;
Search WWH ::




Custom Search