-
Notifications
You must be signed in to change notification settings - Fork 16
State Pattern
Wikipedia's defintion of the state pattern:
The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to encapsulate varying behavior for the same object based on its internal state.
The basic idea behind the pattern is that what you are trying to control has different states. If you have a car, it can either drive forward, brake, reverse, or you could have parked it. To write this behavior of a car in code is not that simple as it first might seem. If we are moving forward and braking, then we don't want to reverse even though the reverse button and the brake button is often the same key. And what if we are reversing and pressing the forward key, should we brake or accelerate? And what if we have more states than just four? Then you will need the state pattern to avoid nested if-else-statements with several booleans.
- State
- Condition
- Transition
- StateMachine
Define a new state type by inheriting from the State
class
using Pancake.Pattern;
public class IdleState : State
{
public override void OnEnter()
{
Debug.Log("Enter Idle State");
base.OnEnter();
}
public override void OnUpdate()
{
Debug.Log("Update Idle State");
base.OnUpdate();
}
public override void OnExit()
{
Debug.Log("Exit Idle State");
base.OnExit();
}
}
using Pancake.Pattern;
public class MoveState : State
{
public override void OnEnter()
{
Debug.Log("Enter Move State");
base.OnEnter();
}
public override void OnUpdate()
{
Debug.Log("Update Move State");
base.OnUpdate();
}
public override void OnExit()
{
Debug.Log("Exit Move State");
base.OnExit();
}
}
- Declare an instance variable of the
StateMachine
class - Perform a transition to a specific state by calling the
ChangeState
method - A transition provides a condition (
IConsition
) that determines the transition from state A to B, add a transition to theStateMachine
using theAddTransition
method
The basic example below illustrates how to use Transition to convert State, when the variable moving is true and the StateMachine
is in idle state it will perform the transition from idle to move state
public class Sample : MonoBehaviour
{
public bool moving;
private StateMachine _stateMachine;
private void Start()
{
_stateMachine = new StateMachine();
var idleState = new IdleState();
var moveState = new MoveState();
_stateMachine.AddTransition(idleState, moveState, ConditionMove);
_stateMachine.AddTransition(moveState, idleState, ConditionIdle);
_stateMachine.ChangeState(idleState);
}
private void Update()
{
_stateMachine.Update();
}
private bool ConditionMove() { return moving; }
private bool ConditionIdle() { return !moving; }
}