- Home /
Is there a way to get a StateMachineBehaviour on a specific State
Something like:
animator.GetCurrentAnimatorStateInfo(0).GetBehaviour<MyStateMachineBehaviour>()
or at least a way to get the State on which a StateMachineBehaviour is. Something like:
foreach (MyStateMachineBehaviour smb in animator.GetBehaviours<MyStateMachineBehaviour>())
print(smb.stateInfo);
If not, why? Is there something I don't understand that makes it bad or useless to need that?
Answer by yanjingzhaisun · Oct 12, 2016 at 06:03 AM
public class AdvancedStateMachineBehaviour : StateMachineBehaviour {
protected AnimatorStateInfo stateInfo;
public AnimatorStateInfo StateInfo
{
get { return stateInfo;}
}
// Use this for initialization
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
this.stateInfo = stateInfo;
}
}
public static class Utilities
{
public static T GetBehaviour<T>(this Animator animator, AnimatorStateInfo stateInfo) where T : AdvancedStateMachineBehaviour {
return animator.GetBehaviours<T>().ToList().First(behaviour => behaviour.StateInfo.fullPathHash == stateInfo.fullPathHash);
}
}
Thanks for the smart workaround. One has to remember to call base.OnStateEnter if overriding OnStateEnter.
Now the question remains: why Unity doesn't seem to expect us to want that?
This approach only works to get states that aready started at least once before.
You can't do that to, for example, add a callback in your behavior to be called when the animator enters that state.
Answer by pankao · Apr 02, 2017 at 10:04 AM
Well you can always use AnimatorChildState.state.behaviours
Your answer
Follow this Question
Related Questions
moving gameobject from state machine behaviour/different code result from inside OnStateExit() 1 Answer
How do I make the transition between two states in the "Animator" happen instantly? 3 Answers
How to Prevent Mecanim from Cloning Behaviours? 1 Answer
Mec Anim transition Bug? 0 Answers
Does anybody have best practices on creating an action-adventurer character (Mecanim)? 0 Answers