Reputation: 101
I want to understand the syntax of coroutines in c# (because it seams really unusual to me...).
When we do something like:
yield return new WaitForSeconds(2.0f);
Firstable: I understand the goal of this statement, but not the syntax.
What does the WaitForSeconds Class represent? It should be of type IEnumerator as this is return type of the function.But according to the doc http://docs.unity3d.com/ScriptReference/WaitForSeconds-ctor.html, this has no return type and it's a Yield Instruction (so confused there)
So what is the purpose of yield in this case ?
And why do we mix it with the return keyword ?
Thank in advance.
Upvotes: 0
Views: 931
Reputation: 1
void Start()
{
//to start a routine
StartCoroutine(A_routine());
//this is same as above
IEnumerator refer_to_A_routine = A_routine();
StartCoroutine(refer_to_A_routine);
}
IEnumerator A_routine()
{
//waits for 0.1 second
yield return new WaitForSeconds(0.1f)
//waits till another_routine() is finished
yield return StartCoroutine(another_routine())
//starts another_routine() there is no wait
StartCoroutine(another_routine())
}
Upvotes: 0
Reputation: 1359
It simply allows you to execute some piece of code in parallel.
for example:
IEnumerator PrintAfterDelay()
{
yield return new WaitForSeconds(5.0f);
//Rest of the code in this method will execute after 5 seconds while all
all other code will be execute in parallel
Debug.Log("Now I am here after 5 Seconds");
}
Call it in Start() for example.
void Start()
{
StartCoroutine("PrintAfterDelay");
Debug.Log("I am here");
}
Upvotes: 0
Reputation: 3367
Using the yield return call creates an IEnumerable of the type that is being returned. This allows the calling function to process a list of values as they are being computed instead of all at once at the end, like if you just returned a collection.
In Unity3d this is important because the draw cycle is basically all happening on a single thread, so you can use coroutines and the yield return syntax to nest behaviors inside your scripts.
The new WaitForSeconds(...) call allows the execution context to return to the outside caller for a period of time while processing a no-op effectively pausing the execution of that MonoBehaviour, without pausing the entire draw thread.
Upvotes: 0