Unity - how to start a timer in parallel with a number of coroutines and WaitForSeconds

In the code below, I have a loop for the appearance and disappearance of enemies.

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 enemyCycleDuration floatwhich

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

Note what fadeTimecomes from FadeToForWeaponand FadeToForEnemy. The idea here is that I want it to enemyCycleDurationrun in parallel with EnemyCycle(), so it reset (see code below) at the same time that

yield return new WaitForSeconds (showTime);

achieved at EnemyCycle()(end of method).

I return enemyCycleDurationas follows in the update method, but EnemyCycle()it seems to be ahead enemyCycleDuration, always ending in enemyCycleDurationreset. How can I get both to run parallel to each other in time and complete simultaneously?

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

timeElapsed = 0;

Debug.Log ("Reset CycleDuration");
    }
}
+4
1

- , , . - :

int TimeBetweenAction1 = 3f;
int TimeBetweenAction2 = 3f;

void Update () {   
    if(Time.time > NextAction1){
        DoAction1();
    }

    if(Time.time > NextAction2){
        DoAction2();
    }

}

void DoAction1(){
    NextAction1 = Time.time + TimeBetweenActions1;
}

void DoAction2(){
    NextAction2 = Time.time + TimeBetweenActions2;
}

. , gameObject, gameObject, Scene...

, , , . , - .

0

Source: https://habr.com/ru/post/1682036/


All Articles