how to add state machine behaviour in unity code example
Example 1: unity state machine behaviour
using UnityEngine;public class AttackBehaviour : StateMachineBehaviour
{
public GameObject particle;
public float radius;
public float power; protected GameObject clone; override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
clone = Instantiate(particle, animator.rootPosition, Quaternion.identity) as GameObject;
Rigidbody rb = clone.GetComponent<Rigidbody>();
rb.AddExplosionForce(power, animator.rootPosition, radius, 3.0f);
} override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
Destroy(clone);
} override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
Debug.Log("On Attack Update ");
} override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
Debug.Log("On Attack Move ");
} override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
Debug.Log("On Attack IK ");
}
}
Example 2: unity state machine behaviour for ai
public class StateMachine<T>
{
private T m_pOwner;
private State<T> m_pCurrentState;
private State<T> m_pPreviousState;
private State<T> m_pGlobalState;
public StateMachine(T owner)
{
m_pOwner = owner;
}
public void SetCurrentState(State<T> state)
{
m_pCurrentState = state;
}
public void SetPreviousState(State<T> state)
{
m_pPreviousState = state;
}
public void SetGlobalState(State<T> state)
{
m_pGlobalState = state;
}
public void StateMachineUpdate()
{
if (m_pGlobalState != null)
{
m_pGlobalState.Execute(m_pOwner);
}
if (m_pCurrentState != null)
{
m_pCurrentState.Execute(m_pOwner);
}
}
public void ChangeState(State<T> newState)
{
m_pPreviousState = m_pCurrentState;
m_pCurrentState.Exit(m_pOwner);
m_pCurrentState = newState;
m_pCurrentState.Enter(m_pOwner);
}
public void RevertToPreviousState()
{
ChangeState(m_pPreviousState);
}
public State<T> CurrentState()
{
return m_pCurrentState;
}
public State<T> PreviousState()
{
return m_pPreviousState;
}
public State<T> GlobalState()
{
return m_pGlobalState;
}
public bool IsInState(State<T> state)
{
return m_pCurrentState == state;
}
}