How to wait for an animation to finished in Unity C#

22,275

Solution 1

You can use Unity's Animation Events (https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html).

They are markers that can be placed in your animation timeline and allow you to specify a function that will be called.

Solution 2

What you can do to wait for the animation to finish is using the time the animation take to complete, which you can find on your animation looking at the inspector, you can simply wait that amount of time after you trigger the animation.

So in your case it would look something like that :

private IEnumerator Die()
{
    // Play the animation for getting suck in
    anim.SetTrigger("Shrink") 

    yield return new WaitForSeconds(animationTime);

    // Move this object somewhere off the screen

}
Share:
22,275
BenjaFriend
Author by

BenjaFriend

Game Design and Development student at RIT

Updated on October 24, 2021

Comments

  • BenjaFriend
    BenjaFriend over 2 years

    I want to wait for an animation clip to finish after I set the trigger.

    private void Start()
    {
        anim = GetComponent<Animator>();
    }
    
    
    private IEnumerator Die()
    {
        // Play the animation for getting suck in
        anim.SetTrigger("Shrink")      
    
        // Wait for the current animation to finish
        while (!anim.IsInTransition(0))
        {
            yield return null;
        } 
    
        // Move this object somewhere off the screen
    
    }
    

    The animation plays, but it doesn't wait to finish before it moves on to the code after the while loop.

    Here is my animator component: enter image description here