Is there any way that I can get the name of the state that is currently active in the animation controller in an animator?
I’ve been looking all over for this, but I can’t find it. I can’t find a variable for it within StateMachineBehavior, I can’t find a function to return the current state name within Animator, and even if I use Animator.GetCurrentAnimatorStateInfo, the AnimatorStateInfo it returns doesn’t have a value for the name of the state.
I can issue a command to play a specific state, and I can check if the current state has a name that matches something I can send it, but I want to just get the actual state’s name.
The animator internally only uses hashes of the names (as int), not the actual strings of the names. In the editor, you might be able to hack yourself around that somehow but in the builds, the original names simply don’t exist.
If you need the names at runtime, you’ll have to build a reverse lookup table that maps hashes back to names. In the editor, you can poke at Animator with reflection to call the private APIs that tell you the names.
//this are variables you get inside the StateMachineBehaviour
Animator _Animator, int _iLayer, AnimatorStateInfo stateInfo
UnityEditor.Animations.AnimatorController _AnimatorController = _Animator.runtimeAnimatorController as UnityEditor.Animations.AnimatorController;
UnityEditor.Animations.AnimatorStateMachine _StateMachine = _AnimatorController.layers[_iLayer].stateMachine;// this is reference to Base Layer
//this is how you get the name of each state inside a for loop
_StateMachine.states[i].state.name
// you can use teh compare to see if name matches
stateInfo.IsName(_StateMachine.states[i].state.name);
lua script is:
function findAnimation(object,animName)
local animator = nil;
animator = object:GetComponent("Animator");
local states = animator.runtimeAnimatorController.layers[0].stateMachine.states;
for i = 0, states.Length - 1 do
local state = states[i];
print("state:"..state.state.name);
if state.state.name == animName then
return true;
end
end
--[0].state.name;
--print("adsfafds:" ..clips);
end
Strangely, there is no built-in way. You have to create a Dictionary<int, string> and populate it with Animator.StringToHash(“Some State Name”), “Some State Name” for every state name in your animation controller. Then you can easily look up the state name from the dictionary by getting the state hash for the current state.
private static Dictionary<int, string> animStateHashToName = new Dictionary<int, string>();
// Populate your dictionary data.
// Then later look it up when you need it.
animStateHashToName[animController.GetCurrentAnimatorStateInfo(0).shortNameHash]