Home > Net >  How to start code after an animation is played in Unity?
How to start code after an animation is played in Unity?

Time:07-04

I need to play like a pop-out animation (growing smaller) and after that move the UI-Elements from the animation out of the canvas.

I've tried various things, like

bool AnimatorIsPlaying(){
     return animator.GetCurrentAnimatorStateInfo(0).length >
            animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
  }

or

 bool AnimatorIsPlaying(){
      return animator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1;
   }

and more, almost all from this https://answers.unity.com/questions/362629/how-can-i-check-if-an-animation-is-being-played-or.html question.

Sometimes, the things, if in an if clause with the bools, didn't move out at all, or they moved out too soon, like if nothing even was added. I've even tried making the method a IEnumerator so that I could do a yield return new WaitForSecondsRealtime(0.25f) but then I couldn't call the method from an other class anymore(which IS neccessary).

Now I've found an Method which is just calling an method from the other class and then starting a Coroutine with yield return new WaitForSecondsRealtime(0.25f). But is there a better method and why da frick was it not working?

CodePudding user response:

Kinda faced a simmilar problem a few weeks ago... this is how I fixed it: I set my AnimationController that it starts the next Animation immediatly after completing the current one. (In case you don't have an Animation afterwards just use an empty one as an Idle State) Then in my Code after starting my Animation I use a Coroutine to wait until the "Idle-Animation" has started. (and therefore your original Animation has ended) It worked perfectly for me so maybe it will work for you too! Here is the code for the Coroutine:

public IEnumerator WaitForAnimationFinished()
{
    yield return new WaitUntil( delegate { return playerAnimator.GetCurrentAnimatorStateInfo(0).IsName("YourIdleAnimationName"); });
    
    // Move the UI-Elements from the animation out of the canvas
} 

I guess it is not the best solution but to make it able to be called from another class you could add a public static MyScriptInstance variable in the Script where you save the Method above. Then you could just call your Method with StartCoroutine(MyScript.MyScriptInstance.WaitForAnimationFinished())

I hope I was able to help you with that! :)

CodePudding user response:

This problem can be worked around in several ways. From a timer counting up/down (with the animation speed variable to count against), to a coroutine (one of my preferences) as Pretzl mentioned.

You can also use Animations Events. Simply create a function with your code to be called, add an event at the end of your animation, and it will be called at that point.

See more about animation events here.

  • Related