How to make sure a coroutine has ended before calling WaitForSeconds

In the code below I have the FadeToForEnemy coroutine. How can I make sure FadeToForEnemy has ended before I call WaitForSeconds?

IEnumerator EnemyCycle()    {
while (isRepeating)
{

    for (int j = 0; j < enemies.Length; j++) {

        Enemy currentEnemy = enemies [j];
        var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
        var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 0f, 1f, currentEnemy.gameObject, false));

 coroutinesToStop.Add(_currentFade);
    }

    yield return new WaitForSeconds (hdTime);

    for (int j = 0; j < enemies.Length; j++) {

        Enemy currentEnemy = enemies [j];
        var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
        var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 1f, 1f, currentEnemy.gameObject, true));

         coroutinesToStop.Add(_currentFade);

    yield return new WaitForSeconds (srTime);

    }
}
}

I think you need to change your code a bit, but you can wait for a Coroutine to finish by using the StartCoroutine function as the yield statement:

yield return StartCoroutine(FadeToForEnemy())
1 Like

So how do I populate coroutinesToStop with your suggestion?

Use a Coroutine variable to hold the result of StartCoroutine, add the value in that variable to your stop list, then yield return that variable. Something like:

 var c = StartCoroutine(blahblah);
 stopCoroutineList.Add(c);
 yield return c;