Search Unity

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

Discussion in 'Animation' started by Thaao, Jan 14, 2020.

  1. Thaao

    Thaao

    Joined:
    Jun 9, 2014
    Posts:
    54
    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.
     
  2. Kybernetik

    Kybernetik

    Joined:
    Jan 3, 2013
    Posts:
    2,570
  3. Inxentas

    Inxentas

    Joined:
    Jan 15, 2020
    Posts:
    278
    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.

    Code (CSharp):
    1. void OnEnd()
    2. {
    3.     Destroy(gameObject);
    4. }
    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.

    Code (CSharp):
    1. void OnEnd()
    2. {
    3.     myInt++;
    4.     if (myInt>3) {
    5.         Destroy(gameObject);
    6.     }
    7. }
    With such a simple solution any external one might be overkill depening on what you are trying to do.
     
    Last edited: Jan 15, 2020
    earth2jeremy likes this.