- Home /
IEnumerator Function
IEnumerator C#
What is this? Why is it used? Why are these used with StartCoRoutine?
Answer by RampantStudios · Oct 28, 2010 at 07:29 PM
Your best bet is the check the documentation as to why they use IEnumerators within Unity. http://unity3d.com/support/documentation/ScriptReference/WaitForSeconds.html http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.StartCoroutine.html
Taken from the StartCoroutine documentation -
The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed. Coroutines are excellent when modelling behaviour over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. This will wait until the coroutine has finished execution.
The IEnumerator allows the program to yield things like the WaitForSeconds function, which lets you tell the script to wait without hogging the CPU
Answer by boymeetsrobot · Oct 28, 2010 at 07:33 PM
StartCoRoutine essentially runs a function in another thread when used in conjunction with yield. We use IEnumerator functionName() as we are essentially spawning a collection of these functions that are iterated through and executed when used with WaitForSeconds. You can think of it as processing functions with a delay, outside of the Update loop.
Take a look at my answer on the post below for an example:- http://answers.unity3d.com/questions/25246/programming-question-with-waitforseconds/25249#25249
Just for clarity - coroutines are not run in another thread, they're essentially just functions which get the current state saved and added to a queue, then resumed when the yield condition is met
Thanks for the explanation $$anonymous$$ike. This was based on assumption because WaitForSeconds seemed very similar to Thread.Sleep :)
t is too bad that unity can still not start new threads. I guess that makes a big deal to the whole unity layer. Luckily some internal functions like LoadlevelAsync() will load the level in a new thread...