Search Unity

Feedback Animator.HasState(int layer, string stateName) overload should be added

Discussion in 'Scripting' started by realkillerx, May 5, 2021.

  1. realkillerx

    realkillerx

    Joined:
    Nov 9, 2013
    Posts:
    10
    The current implementation of Animator.HasState only takes an argument of layer and state ID.
    We can easily add this by turning the state name into a int with the Animator.StringToHash function and then calling the HasState function, i think this should be added as a overload to make the API more friendly.

    The example code would be like this:

    Code (CSharp):
    1. public bool HasState(int layerIndex, string stateName)
    2. {
    3.   return HasState(layerIndex, StringToHash(stateName));
    4. }
     
    LuckyMisterSleven likes this.
  2. SOICGeek

    SOICGeek

    Joined:
    Jun 25, 2019
    Posts:
    78
    I agree. In the meantime, you can turn this into an extension method. Here's what I use:
    Code (csharp):
    1.  
    2.        [MethodImpl(MethodImplOptions.AggressiveInlining)]
    3.        public static bool hasState(this Animator anim, string stateName, int layer = 0) {
    4.  
    5.            int stateID = Animator.StringToHash(stateName);
    6.            return anim.HasState(layer, stateID);
    7.  
    8.        }
    9.  
    Line 2 gives the compiler a hint to aggressively inline the code for this, hopefully to reduce function call overhead.

    I agree, though, that figuring out how to get that stateID was an exercise in frustration for me.