In the code below, I am running a coroutine on each element of an array of game objects. How can I stop running the FadeToForEnemy coroutine on each game object?
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));
}
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));
yield return new WaitForSeconds (srTime);
}
}
}
UPDATE
I tried stopping the coroutines in the following but the cycle of fading in and out just continued.
public void StopEnemyCycles () {
for (int i = 0; i < enemies.Length; i++) {
enemies [i].StopAllCoroutines ();
}
StopCoroutine ("EnemyCycle");
}
Also below is FadeToForEnemy:
IEnumerator FadeToForEnemy(Material material, float targetOpacity, float duration, GameObject gameObj, bool isEnabled) {
// Cache the current color of the material, and its initiql opacity.
Color color = material.color;
float startOpacity = color.a;
// Track how many seconds we've been fading.
float t = 0;
if (isEnabled) {
gameObj.GetComponent<BoxCollider2D> ().enabled = isEnabled;
}
while(t < duration) {
// Step the fade forward one frame.
t += Time.deltaTime;
// Turn the time into an interpolation factor between 0 and 1.
float blend = Mathf.Clamp01(t / duration);
// Blend to the corresponding opacity between start & target.
color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);
// Apply the resulting color to the material.
material.color = color;
// Wait one frame, and repeat.
yield return null;
}
if (!isEnabled) {
gameObj.GetComponent<BoxCollider2D> ().enabled = isEnabled;
}
}
I have several groups of enemies, each group fades in and out at the same time.
BoxColliders? \$\endgroup\$