Friday, September 25, 2015

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


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().material;
var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 0f, fTime, currentEnemy.gameObject, false));


coroutinesToStop.Add(_currentFade);

if (currentEnemy.hasWeapon) {
weaponCycleCoroutines.Add(StartCoroutine(FadeToForWeapon(currentEnemy.weapon.GetComponent().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().material;
var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 1f, fTime, currentEnemy.gameObject, true));

coroutinesToStop.Add(_currentFade);
if (currentEnemy.hasWeapon) {
weaponCycleCoroutines.Add(StartCoroutine(FadeToForWeapon(currentEnemy.weapon.GetComponent().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().


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");
}
}


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...