Destroy a game object after an animation

Hi,
As the title says I’m trying to destroy a game object after its dying animation. As I found on the Internet, I tried to use a Coroutine. However, my code does not work and the game object is destroyed before his animation even starts. Why so ?

private void OnTriggerEnter2D(Collider2D other)
    {
         animator.SetTrigger("isBiting");
         float length = animator.GetCurrentAnimatorStateInfo(0).length;
         StartCoroutine(WaitBeforeDestroyHuman(length));
         Destroy(human);
    }

    IEnumerator WaitBeforeDestroyHuman(float length)
    {
        yield return new WaitForSeconds(length);
    }

Review how coroutines work. The above won’t do what you expect.

You may be able to eliminate all use of coroutines by simply supplying the optional second argument to Destroy(), which tells Unity how long to wait before actually destroying the thing.

Go see the Destroy() docs for more about the optional second argument.

Thank you Kurt ! However, the object now despawns too fast, which is a little strange to me since I did put the animation length in the second parameter.

float length = animator.GetCurrentAnimatorStateInfo(0).length;
            Destroy(human, length);

Maybe the state length isn’t tied precisely to the animation length?

I’ve never done things this way. The reference way is to use an AnimationEvent.

I read elsewhere that animator.GetCurrentAnimatorStateInfo(0).length doesn’t take into account the Speed variable set in the animator, so the actual length will be different if you have the speed set to anything but 1.

so maybe reading the speed variable as well and dividing by that should fix it?