Coroutine being detected as inactive despite being active

1.8k views Asked by At

In my game, I'd like to have the enemy flash before it does its attack. I created a Flash() coroutine that does this, but when I try to run the coroutine, I get the following error:

"Coroutine couldn't be started because the the game object 'Sheep' is inactive!"

The thing that makes this especially confusing is that I have checked for whether the object that holds the Animal.Flash() coroutine is active and it is:

Animal oldAnimal = (GameObject.FindWithTag ("EnemyAnimal").GetComponent<Animal> ()) as Animal;

            Debug.Log("Active? " + oldAnimal.gameObject.activeInHierarchy);
            StartCoroutine(oldAnimal.Flash());

Sheep inherits from Animal, which is a Monobehavior. I'm at a loss as to what is happening here.

Edit: The Debug.Log() above returns True.

Edit2: As an alternative method of flashing, I tested an animation through oldAnimal, which works fine, indicating that the coroutine is the problem, not oldAnimal's lack of existence. So weird.

Animator changeAnimation = (oldAnimal.GetComponentInChildren<Animator> ()) as Animator;
            changeAnimation.SetTrigger ("Attack"); // This works fine.

To clarify, I don't want to go this way because it involves creating animations for every creature in the game, while creating a coroutine that changes the color of the sprite of whichever creature is selected can be applied universally.

Here is the coroutine:

public virtual IEnumerator Flash(){ 
    Color white; // Pure white.
    Color original; // Original color of animal sprite.
    color = GetComponent<SpriteRenderer> ().color; // Color of the animal.

    original = color;

    white.r = 255;
    white.b = 255;
    white.g = 255;
    white.a = 255;
    int i = 0;

    for (float f = 1f; f >= 0; f -= 0.008f) { // f -= controls the speed of the fade
        if (i == 0) {
            color = original;
            yield return null;
        }
        if (i == 1) {
            color = white;
            yield return null;
        }
    }
    color = original;
}
1

There are 1 answers

2
Atra Viator On BEST ANSWER

StartCoroutine is a method of MonoBehaviour. So, whichever script actually uses StartCoroutine is actually the object that needs to be active.

You may want to try oldAnimal.StartCoroutine(oldAnimal.Flash());