Home > Back-end >  How to do something when an animation ends? (Unity)
How to do something when an animation ends? (Unity)

Time:11-28

After an enemy gets shot, I need them to play a death animation and then get disabled.

        anim.Play("Destroy", 0, 0f);  
        while (anim.GetCurrentAnimatorStateInfo(0).normalizedTime < 1f)
        {
            yield return null;
        }
        gameObject.SetActive(false);

However, since there is already a different animation happening in the background, the normalizedTime is usually something like 15.035. When I change the condition to this:

((anim.GetCurrentAnimatorStateInfo(0).normalizedTime % 1) > 0f)

the enemy gets disabled immediately.

I also tried resetting the normalisedTime to 0 after playing the animation, but I don't know how. I found a guide saying I should use anim["Destroy"].normalizedTime = 0f;, but that ends up returning error CS0021. What am I doing wrong?

CodePudding user response:

Best way to do that is by animation events. If you write a MonoBehaviour script that has a public function in it and add it to the object where the Animator component exists then you can edit your animation and add an "Animation Event" at the end of the animation and then in the inspector choose the right function

  • Related