Coroutine Not Looping on Update?

 IEnumerator Narrate()
    {

        print ("looping for " + index + " of " + narrations.Count);

        //if list is not finished
        if (index <= narrations.Count - 1)
        {
            foreach(string text in currentNarration.texts)
            {
               
                print(text.ToString() + " index: " + index);
                yield return new WaitForSeconds(currentNarration.waitBtwTexts);
            }
            index++;
            //print("index: " + index);
            currentNarration = narrations[index];
            yield return new WaitForSeconds(currentNarration.waitBeforeNext); 
        }
    }

void Update()
    {
        if (startNarration)
        {
            startNarration = false;
            StartCoroutine(Narrate());

        }
}

I have to use the startNarration bool because when I plainly start coroutine in update, the results come in all tangled and it completely ignores the wait expressions.

Code in Update happens every frame. You would be starting a new coroutine every frame, so everything will start cascading and repeating very quickly. You could use a for loop instead of an if statement and loop over the whole thing from inside the coroutine:

for (int index = 0; index < narrations.Count; index++)
// instead of
if (index <= narrations.Count - 1)

In this case, remove the class field for index and don’t increment index inside the body. Then either keep the coroutine starting within Update as-is, or call StartCoroutine in a Start method since code in Start only runs once.

1 Like

Thank you :slight_smile: Embarrassingly, I came up with a simple solution seconds after my post. I just added StartCoroutine(Narrate()) to the end of my coroutine, which makes it loop in itself. hah.

2 Likes