Home > Software design >  Using a Coroutine in a loop
Using a Coroutine in a loop

Time:10-23

I have a question about coroutines in a loop. More specific about how I can achieve it that my loop continues to check the condition until the waitForSeconds in the coroutine are over.

I have attached a screenshot of my code. My problem is that the Line "Now I am executed" is shown right after myAudio.Play(); It makes sense since the coroutine only waits for the statements after the yield return but how can I make it work with the for loop?

Any help would be appreciated! Thank you so much.

enter image description here

CodePudding user response:

StartCoroutine starts each IEnumeratoras a new Coroutine and immediately continuous with the rest of the code.

So as said without having further context of your code what you would do is something like

private void playDBStack()
{
    fillList();

    StartCoroutine(playDBStackRoutine())
}

private IEnumerator playDBStackRoutine()
{
    for(var i = 0; i < 2; i  )
    {
        // executes playAudio and waits for it to finish
        yield return playAudio();
    }
}

private IEnumerator playAudio()
{
    var x = chooseList(score);
    // executes PlayAndWait and wait for it to finish
    yield return PlayAndWait(x);
}

this way you execute and at the same time wait until the IEnumerators are finished before going to the next one.


Some further notes:

  • The line

     myAudio.GetComponent<AudioSource>();
    

    does absolutely nothing.

  • The entire method updateScore in its current state could simply be replaced by using

     score  ;
    

    I would consider a method that can be replaced by a simple operator "code smell" ;)

  • Related