Skip to main content

Animator State Query

It is possible to query the runtime animator's internal state using the AnimatorStateQueryAspect aspect. State and transition data returned by this aspect contain a hash of state/transition respectively and normalized time (how much time controller is in this state/transition). To find out the required state, the hash value of it must be calculated upfront. This should be done by constructing FixedStringName with a state name. For example, a state with the name "Idle Random" can be used as follows:

var stateNameFull = new FixedStringName("Idle Random");

Hash code can be obtained from this string by calling CalculateHash32() member function:

var stateHash = stateNameFull.CalculateHash32();

For transitions, the process is the same:

Transition Name

var transitionName = new FixedStringName("Turn Right -> Turn Left");
var transitionHash = transitionName.CalculateHash32();

Here is a usage example of AnimatorStateQueryAspect:

public partial struct MySystem : ISystem
{
uint myStateHash, myTransitionHash;

public void OnStart(ref SystemState state)
{
myStateHash = new FixedStringName("State Name").CalculateHash32();
myTransitionHash = new FixedStringName("State Name -> State Other Name").CalculateHash32();
}

public void OnUpdate(ref SystemState state)
{
foreach (var animatorState in SystemAPI.Query<AnimatorStateQueryAspect>())
{
// Specify required layer index of animator.
var layerIndex = 0;

// Get animator current state
var runtimeState = animatorState.GetLayerCurrentStateInfo(layerIndex);

// Use received RuntimeStateInfo structure to access to the current state hash, and normalized state time
if (runtimeState.hash == myStateHash)
{
// Do something...
}

// Get current transition
var transitionState = animatorState.GetLayerCurrentTransitionInfo(layerIndex);
if (myTransitionHash === transitionState.hash)
{
// Do something...
}
}
}
}

If the RUKHANKA_DEBUG_INFO script symbol is defined in the project, RuntimeTransitionInfo and RuntimeStateInfo structures will contain a name field with a transition/state symbolic name in it. There is an example named Animator State Query in Rukhanka samples. It shows described above features.