Home > OS >  How to wait until animation is finished when using Animator?
How to wait until animation is finished when using Animator?

Time:11-12

This is a beginner question that should be available from the first google result but I can't find it.

I have this method that plays an animation using an Animator:

IEnumerator popDownAnimation(string c)
{
    animator = GetComponent<Animator>();
    animator.Play("Pop Down Animation");
    yield return new WaitUntil(() => animator.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !animator.IsInTransition(0));
    animator.Play("New State");
}

Can't remember where I got it from, but yield return new WaitUntil(() => animator.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !animator.IsInTransition(0)); isn't working. It's instantly jumping from "Pop Down Animation" to "New State", so the "Pop Down Animation" doesn't have a chance to play.

CodePudding user response:

I would suggest using Animation events to do whatever you need. Just remember to make a public method and add the animation event at the end of your animation.

CodePudding user response:

Try this

IEnumerator popDownAnimation(string c)
{
   animator = GetComponent<Animator>();
   animator.Play("Pop Down Animation");
   float animationLength = animator.GetCurrentAnimatorStateInfo(0).length;
   yield return new WaitForSecondsRealtime(animationLength);
   animator.Play("New State");
}

However, like @NotVeryGoodAtThis mentioned, I wouldn't do this in code unless you have a specific reason why you can't make it work using animation events or using parameters within the animator to transition between animation states. Designing your animation using Unity's Animator window and using states, parameters, and transitions will be easier to manage than doing it through code, especially as your animators become more complicated.

  • Related