(2D) How to tell when an animation has finished or looped n times in script?

I’m wanting something to happen once an animation has finished or once it has looped so many times in script. But I don’t know how to “tell” that an animation has finished or looped so many times in the script.

Not sure if this should go in Scripting or Animation or 2D.

I highly recommend you check out Animancer (link in my signature) which makes it really easy to wait for animations to finish (and the new documentation for the upcoming v4.0 update explains how to do it in much more detail).

Otherwise, this page briefly summarises a few ways you can do it when using a Mecanim Animator Controller.

Look into Animation Events for native solution. If you right-click on the dark grey area above an animation’s keyframes you get a context menu that will allow you to add one. You can then enter a few parameters for it. In my game I use the “function” parameter to execute a a method on the animated GameObject.

void OnEnd()
{
    Destroy(gameObject);
}

This method just removes the gameObject instantly, but you could just as well let it bump up an int before you do anything. In this example the gameObject is destroyed after a few animation loops.

void OnEnd()
{
    myInt++;
    if (myInt>3) {
        Destroy(gameObject);
    }
}

With such a simple solution any external one might be overkill depening on what you are trying to do.

1 Like