Search Unity

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

Discussion in 'Scripting' started by BenjaFriend22, Mar 18, 2017.

  1. BenjaFriend22

    BenjaFriend22

    Joined:
    Sep 29, 2016
    Posts:
    13
    I want to wait for an animation clip to finish after I set the trigger.


    Code (CSharp):
    1.   private void Start()
    2.     {
    3.         anim = GetComponent<Animator>();
    4.     }
    5.  
    6.  
    7.     private IEnumerator Die()
    8.     {
    9.         // Play the animation for getting suck in
    10.         anim.SetTrigger("Shrink")    
    11.  
    12.         // Wait for the current animation to finish
    13.         while (!anim.IsInTransition(0))
    14.         {
    15.             yield return null;
    16.         }
    17.  
    18.         // Move this object somewhere off the screen
    19.  
    20.     }
    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: animator.PNG
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @BenjaFriend22

    Hi there,

    you could take look at StateMachineBehaviour in scripting manual.

    Maybe you could put your code into method OnStateExit, this should be run on end of state.
     
    dyupa likes this.