Search Unity

What I'm doing to sync Animations to Code Stuff

Discussion in 'Scripting' started by esitoinatteso, May 4, 2015.

  1. esitoinatteso

    esitoinatteso

    Joined:
    Sep 23, 2013
    Posts:
    26
    Hi there and thanks for jumping in!

    I've been using Unity for a while now and, though I'm no expert, I'd like to share the solution I use to synchronise animations and code execution because this is something I always tried to do in the previous versions and I never achieved it that well.

    I hope it can help other newbies the way I wanted to be helped some time ago and also that this gets showed with higher priority than older threads about this subject by Google ( threads about Get Animation Length, for example).

    So, to sync Animations to Code I take advantage of the new State Machine Behaviours.

    I put this inside the desired State of the Animator:
    Code (CSharp):
    1.     // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
    2.     override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
    3.    
    4.         animator.ResetTrigger("Example");
    5.     }
    And then, from a script that has a reference to that Animator, I use IFs like these:
    Code (CSharp):
    1. if(<Some_Additional_Conditions> && !anim.GetBool("Example")){
    2.  
    3.                     animator.SetBool("Example", true);
    4.  
    5.                     //Do something
    6.                 }
    This way, even inside the Update that code gets executed once and waits for the animation to finish before letting the user to execute it again.

    If the State Machine of the Animator is done correctly, this will prevent odd behaviours to happen.

    Again, I'm no expert and if you think this could be improved somehow, please leave a comment below: this is just my two cents!
    And if it turns out a thread like this already exists, my apologies! :eek: