I need a API or a walk-around like this
**bool Animator::Exist(String stateName, int layerId);**
I know I can use try-catch on animator.Play(stateName, layerId) call, but I hate that.
Any idea?
I need a API or a walk-around like this
**bool Animator::Exist(String stateName, int layerId);**
I know I can use try-catch on animator.Play(stateName, layerId) call, but I hate that.
Any idea?
This as an extension method:
using System.Collections;
using UnityEngine;
public static class Extensions
{
public static bool StateExists( this Animator animator, int stateId, int layerId = 0 )
{
bool stateExists = false;
UnityEditorInternal.AnimatorController ac = animator.runtimeAnimatorController as UnityEditorInternal.AnimatorController;
UnityEditorInternal.StateMachine stateMachines = ac.GetLayer(layerId).stateMachine;
for ( int i = 0; stateMachines != null && i < stateMachines.stateMachineCount; ++i )
{
UnityEditorInternal.StateMachine sm = stateMachines.GetStateMachine(i);
if ( sm != null && sm.stateCount != 0 )
{
for ( int s = 0; s < sm.stateCount; ++s )
{
UnityEditorInternal.State state = sm.GetState(s);
if ( state.uniqueNameHash == stateId )
{
stateExists = true;
break;
}
}
}
}
return stateExists;
}
public static bool StateExists( this Animator animator, string stateName, int layerId = 0 )
{
return animator.StateExists( Animator.StringToHash(stateName), layerId );
}
}
Unfortunately, this code only compiles in the Editor, not at runtime (Player).