Game Development Reference
In-Depth Information
Yielding
The Coroutines and IEnumerator feature are perfectly valid, but C# added a new operator
in Version 2 (Unity now supports V4) called the yield operator. The yield operator
suspends the current method on the current instruction line until the operation is complete;
however, it also allows the CPU to continue in between each result that is returned by the
called method or the instruction. The following example will pause the loop for two
seconds in between the iterations while retuning the control back to the process.
Here's an example; say we have a function to print 10 lines:
IEnumerator Print10Lines()
{
for (int i = 0; i < 10; i++)
{
print("Line" + i.ToString());
yield return new WaitForSeconds(2);
}
}
When the preceding code runs, it will simply loop 10 times, and each time it will print out
the line number. However, before continuing, it will wait for 2 seconds.
Note
Do not confuse IEnumerator with IEnumerable . Coroutines and the yield
keyword only work in a method that returns an IEnumerator feature. This is an easy
mistake that can leave you scratching your head for hours.
Search WWH ::




Custom Search