Pause the coroutine inside a loop

Is it possible to wait for x seconds between every item in the for loop?

Like:

for(int i = 0; i < 4; i ++) {

Debug.Log(i.ToString());

yield return new WaitForSeconds(1);

}

This would works like so: do the code of the for one time, pause the corotine until WaitForSeconds is complete.

When I did this it’s just printing 0, 1, 2, 3 every frame. I want it to print:

0…(wait 1 second)…1…(wait 1 more second)…2… and so on…

Any help would be appreciated!

Thanks from now!

The above code must have been called via a ‘StartCoroutine’ function, otherwise it won’t be used by the MonoBehaviour’s coroutine scheduler, and will all run at once!

Hence:

IEnumerator PrintNumbers(int countUpTo, float waitTime)
{
    for(int i = 0; i < countUpTo; i ++) {
        Debug.Log(i.ToString());
        yield return new WaitForSeconds(waitTime);
    }
}

// elsewhere...

StartCoroutine(PrintNumbers(4, 1)); // Prints your numbers, waits!