Home > other >  UNITY2D: Trouble running a CoRoutine from another script
UNITY2D: Trouble running a CoRoutine from another script

Time:05-03

I have written a function on a script that activates when the player loses all his lives. That calls a CoRoutine in a script attached to my main character that makes a simple death animation and then moves to the game over screen. Debug.Log shows that the function calls, and when I use non-CoRoutine functions attached to the main character, those functions call to. However, the CoRoutine itself never calls, not even showing the log of it ever activating? Does anyone know what is up?

Code included below:

if (GameObject.Find("Heart 1") == null)
        {
            Debug.Log("Naw");
            player.DeathAnimation(20);
            Debug.Log("still not working");
        }


public IEnumerator DeathAnimation(int i)
    {
        int k = i;
        Debug.Log("Numerator works");
        transform.Rotate(Vector3.forward * 9);
        yield return new WaitForSeconds(.08f);
        k--;
        Debug.Log(k);
        if (k <= 0)
        {
            SceneManager.LoadScene("Game Over");
            yield break;
        }
        StartCoroutine(DeathAnimation(k));
    }

CodePudding user response:

There doesn’t seem to be a reason to make this a recursive coroutine. I’d suggest removing the recursion which might also solve the issue you’re having or at least make it simpler to identify.

    if (GameObject.Find("Heart 1") == null)
    {
        Debug.Log("Hmm");
        StartCoroutine( player.DeathAnimation(20) );
        Debug.Log("maybe working");
    }

public IEnumerator DeathAnimation(int i)
{
    Debug.Log("Numerator works");
    for( ; i>0; i-- ) {
        transform.Rotate(Vector3.forward * 9);
        yield return new WaitForSeconds(.08f);
        Debug.Log(i);
    }
    SceneManager.LoadScene("Game Over");
}
  • Related