Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Best way to know when animation enter/exit a state?

Discussion in 'Animation' started by Abdo023, Jan 13, 2018.

  1. Abdo023

    Abdo023

    Joined:
    Dec 18, 2017
    Posts:
    52
    I would like to ask about the proper way of detecting when the animator enters/exits certain states. For example, let's say I have an Idle state and an Attack state and I would like to know which is currently playing.
    here is my code:
    Code (CSharp):
    1.  
    2. Animator anim;
    3. int attackStateHash = Animator.StringToHash( "Base Layer.Attack" );
    4.  
    5. public void Attack () {
    6.         AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0);
    7.         if ( stateInfo.nameHash != attackStateHash) {
    8.          
    9.             anim.SetTrigger ("Attack");
    10.         }
    11.    
    12.     }
    This code kinda works, but the player can trigger the Attack state again before it even finishes playing. I'm feeling it's a bit redundant especially when I have multiple states that I need to check for.
    Is there a more efficient way of doing this?
     
    Last edited: Jan 13, 2018
  2. jdcart23

    jdcart23

    Joined:
    Jan 17, 2018
    Posts:
    12
  3. StickyHoneybuns

    StickyHoneybuns

    Joined:
    Jan 16, 2018
    Posts:
    207
    You can use the state machine as mentioned above to check OnStateExit. If you don't want to redo anything though you simply check it yourself by adding a timer. You know how long each animation is so simply create a timer that keep track at the start of the animation playing.

    Example:
    Code (CSharp):
    1. float elapsedTime;
    2. private bool attackFlag;
    3.  
    4. void Start()
    5. {
    6. attackFlag = false;
    7. }
    8.  
    9. void Update()
    10. {
    11. if(attackFlag == True)
    12. {
    13. elapsedTime += Time.unscaledDeltaTime;
    14. }
    15. if(elapsedTime >= "input your time needed for animation to play")
    16. {
    17. attackFlag = false;
    18. elapsedTime = 0;
    19. }
    20. }
    21. public Void Attack()
    22. {
    23. if(attackFlag == false && "whatever other event you check for")
    24. {
    25. elapsedTime=Time.unscaledDeltaTime;
    26. anim.SetTrigger("Attack");
    27. attackFlag = true;
    28. }
    29. }
     
unityunity