What is Coroutine, Yiel and IENumerator?
I try but it seem like I can't really understand the concept at all.
Can you explain it in the easy way please?
Answer by JedBeryll · May 15, 2016 at 06:28 PM
A coroutine is a method that you can execute through several frames opposite to a regular method which must execute completely within 1 frame. If you want to start a coroutine you create the method as an IEnumerator and you can't just call it like a regular function, it needs to be started with StartCoroutine(FunctionName(parameters)); example:
void Start() {
StartCoroutine(Wait(3f));
}
IEnumerator Wait(float sec) {
yield return new WaitForSeconds(sec);
print("complete");
}
This would wait 3 seconds then print "complete". Only a monobehaviour can start a coroutine, and it must contain a yield statement. Check the unity manual though it gives you a much better explanation than i do. http://docs.unity3d.com/Manual/Coroutines.html
This is right but a bit wrong, a coroutine does not differentiate from a regular method because it runs over several frames.
IEnumerator WrongExampleOfCoroutine(){
if(true) yield break; // Done in the same frame
// $$anonymous$$ore code that will not happen
}
A coroutine is a method that can run over several frames and be completed or stopped when done with it. It allows to run code that should be temporary (tho it could replace the Update method if using a while(true) loop). It also offers extra control as to when in the frame it will be continued.
http://docs.unity3d.com/$$anonymous$$anual/ExecutionOrder.html
If you program in some mega intensive task.
for(everAndEver)
{
for(everAndEver)
{
Do LOTS AND LOTS
}
} //Dont try this 'code'
And try to jam it in to Update or a normal function it will clog up the cpu for a while.
Putting in yield statements allows you to tell it to stop what its doing at some point in that code and come back to it next frame. It spaces out the processing to stop it hogging everything.
Using yield statements can only be done in a coroutine.
Your answer
Follow this Question
Related Questions
Why cant I access the same function twice? 0 Answers
How can i change the value of a variable from an IEnumerator 0 Answers
"Can't add script behaviour AICharacterControl. The script needs to derive from MonoBehaviour!" ? 2 Answers
Need help with c# 1 Answer
[C#] Coroutine just won't stop! 2 Answers