Why would an internal loop modify a coroutine?

Can somebody explain to me what is the difference between these coroutines? Since I have to call the function each time either way, don't they, in effect, do the same thing?

IEnumerator MyRoutine()
{
    
        yield return null;
        Debug.Log("Hello");
}

IEnumerator MyRoutine2()
{
    while (true)
    {
        yield return null;
        Debug.Log("Hello");
    }
}

Why does the first one runs only once and the second forever?


Coroutines are important when they are invoked multiple times. On first invocation, they execution will start from { part. And it will run till the keyword(s) yield return get(s) executed. Now, when the same coroutine is invoked again, code will continue from last yield return executed - next line / statement will be invoked.


Looking at your first example (statement), on first invocation the Coroutine will return null. On 2nd invocation, it will hit Debug.Log("Hello") and ends at }.

Compared to 2nd example (statement), where you have the while(true) { } loop. For first run those parts get executed:

{
    while (true)
    {
        yield return null; // ends here

This is pretty much the same as before. But on 2nd execution the behavior will change. It will run Debug.Log("Hello") again, but then it reaches end of while(true) { } loop, it checks for its condition (it is true) and goes again back to statement yield return null where it ends.