Unity - How to run a timer in parallel to a series of coroutines and WaitForSeconds

Viewed 247

In the code below, I have a cycle for enemies appearing and disappearing.

IEnumerator EnemyCycle()    {
while (isRepeating)
{

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

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

coroutinesToStop.Add(_currentFade);

if (currentEnemy.hasWeapon) {
            weaponCycleCoroutines.Add(StartCoroutine(FadeToForWeapon(currentEnemy.weapon.GetComponent<Renderer>().material, 0f, fadeTime, currentEnemy.weapon, false)));

        }
}

yield return new WaitForSeconds (hideTime);

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

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

 coroutinesToStop.Add(_currentFade);
 if (currentEnemy.hasWeapon) {
weaponCycleCoroutines.Add(StartCoroutine(FadeToForWeapon(currentEnemy.weapon.GetComponent<Renderer>().material, 1f, fadeTime, currentEnemy.weapon, true)));
}
yield return new WaitForSeconds (showTime);

        }
    }
}

I have an enemyCycleDuration float which is

enemyCycleDuration = 60*(hideTime + fadeTime + showTime + fadeTime)

Note that fadeTime comes from FadeToForWeapon and FadeToForEnemy. The idea here is I want the enemyCycleDuration to be run in parallel to EnemyCycle() so it is reset (please see code below) at the same time that

yield return new WaitForSeconds (showTime);

is reached in the EnemyCycle() (end of method).

I am resetting enemyCycleDuration in the following way in the update method but EnemyCycle() seems to be ahead of enemyCycleDuration, always completing before enemyCycleDuration is reset. How can I get both to run parallel to each other in timing and complete at the same time?

if (canStartUpdatingReset)  {
timeElapsed +=1;
if(timeElapsed >= enemyCycleDuration) {

timeElapsed = 0;

Debug.Log ("Reset CycleDuration");
    }
}
1 Answers
Related