I am confused and curious about how coroutines (in Unity3D and perhaps other places) work. Is coroutine a new thread? Unity's documentation they said:
A coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes.
And they have C# examples here:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Start() {
print("Starting " + Time.time);
StartCoroutine(WaitAndPrint(2.0F));
print("Before WaitAndPrint Finishes " + Time.time);
}
IEnumerator WaitAndPrint(float waitTime) {
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint " + Time.time);
}
}
I have many questions about this example:
In the example above, which line is the coroutine? Is
WaitAndPrint()a coroutine? IsWaitForSeconds()a coroutine?In this line:
yield return new WaitForSeconds(waitTime);, why bothyieldandreturnare present? I read in Unity documentation that "The yield statement is a special kind of return, that ensures that the function will continue from the line after the yield statement next time it is called." Ifyieldis a specialreturn, what isreturndoing here?Why do we have to return an
IEnumerator?Does
StartCoroutinestart a new thread?How many times has
WaitAndPrint()been called in the above example? Didyield return new WaitForSeconds(waitTime);really returned? If yes then I guessWaitAndPrint()was called twice in the above code. And I guessStartCoroutine()was callingWaitAndPrint()multiple times. However, I saw another Unity documentation that says: "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." These words make me feel thatWaitAndPrint()actually has not returned; it was merely paused; it was waiting forWaitForSeconds()to return. If this is the case, then in the above codeWaitAndPrint()was called only once, andStartCoroutinewas just responsible for starting the function, not calling it multiple times.