A versatile and extensible state machine class for c#
-
Define enums for your states
public enum State {WALK, RUN, CLIMB, DIE};
-
Define a list of state data
State data is constructed with the following arguments:
- state name (enum)
- state enter callback (can be null)
- state exit callback (can be null)
- valid transitions (a list of state name enums) if empty can transition to any state
- a boolean determining if this state can be transitioned back to from the next state (optional)
StateData<GameState>[] stateList = new StateData<GameState>[]
{
new StateData<GameState> (State.WALK, OnStartWalking, OnStopWalking, new GameState[]{State.RUN, State.CLIMB, State.DIE}),
new StateData<GameState> (State.RUN, OnStartRunning, OnStopRunning, new GameState[]{GameState.WALK, State.CLIMB, State.DIE}),
new StateData<GameState> (State.CLIMB, OnStartClimbing, OnStopClimbing, new GameState[]{GameState.WALK, State.DIE}),
new StateData<GameState> (State.DIE, null, null)
}
-
Initialize state machine with state list (State machine is generically typed with state enum type)
StateMachine<State> stateMachine = new StateMachine<State>(stateList);
-
Set initial state
stateMachine.SetInitialState(State.WALK);
-
Transition to another state
stateMachine.ChangeState(State.RUN);
-
Add a new state
StateData<State> newState = new StateData<State> (State.DANCE, OnStartDancing, OnStopDancing); stateMachine.AddState(newState);
The MIT License (MIT). Please see License File for more information.