Unity WaitForSecondsRealtime doesn't working when time.timescale = 0

Viewed 45

I have an animation that I want to play after my character dies. I'm trying to activate the Game Over screen after this animation is complete, but it doesn't work after yield return new WaitForSecondsRealtime(3f);

Here is my code:

private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "DeathArea")
        {
           StartCoroutine(Dead());
        }
    }


IEnumerator Dead() 
    {   
        animDie.SetActive(true);
        animDeath.SetTrigger("Die");
        Time.timeScale = 0;
        yield return new WaitForSecondsRealtime(3f);
        animDie.SetActive(false);
        isDead = true;
        deathScreen.SetActive(true);
        managerGame.Medal();
    }

Thank you!

4 Answers

The coroutine is firing off, and Time.timescale is surely breaking things. I'd use it very sparingly if I were you, as this setting also persists between scenes.

You could add an event/function to be called at the end of your animation. Unity lets you do that through the Animation window really easily.

Add an event:

enter image description here

Choose your function from an attached script: enter image description here

I finally found the solution to the problem.

Using the Time.timeScale = 0; code is not a problem. The real problem is that I destroyed my character because it's a death animation. Since my character died, the rest of the code became inoperable.

So instead of killing it, I made it invisible using localScale.

But the solution above is much more useful. Thank you for your answers.

Please change WaitForSecondsRealtime(3f) to WaitForSeconds(3f)

result yield return new WaitForSeconds(3f);

Related