Search code examples
c#unity-game-enginestatesanimator

How to check if an object in an empty state?


How to check if an object with animator is currently in an empty state?

I need to disable the object using SetActive(false), so that:

  • if the object is in transition between states - finish the transition and then disable it.

  • if the object is in default empty state - disable it immediately.

This code works if the object is in transition, but doesn't work if it is in empty state:

MyObject.GetComponent<Animator>().IsInTransition(0)

Solution

  • Ok here's how I did it.

    I'm assuming you know the name of your "default empty state" that you want to disable your object in.

    Declare a static int variable which has the "default empty state" as a string to hash like this:

     static int VAR-NAME = Animator.StringToHash("Base.NAMEOFSTATE");
    

    This is assuming that your base layer is called "Base".

    Then in Update(), put the current state in a variable like this:

    currentState = anim.GetCurrentAnimatorStateInfo(0);
    

    and then use an If statement to check if your "default empty state" is equal to the current state like this:

    if (currentState.nameHash == VAR-NAME){
          Debug.Log("Do Stuff Here");
     }
    

    Have fun coding!