Creating a Finite State Machine (FSM) for a game (or application) can start off with a simple diagram drawn on some scrap paper and implemented in Unity with a series of Switch conditions. However, that soon becomes difficult to visualise and therefore unmanageable. However, Unity already has a built in visualised FSM — the Animator.
Consider a simple FSM where a character is either “Thinking”, “Attacking” or “Dead”.
Creating this as Animator states is really simple. We have control of what drives the state change (the Parameters), we can visualise the changes at run time and test them by manually changing the parameters.
Now how to synchronise the game loop with the states? The first step is to create code for each separate State. E.g. for the “Thinking” state;
To make this is a little easier I created a base class for the StateBehaviours to derive from.
The StateMachineBehaviour has a number of On<Message> handlers, I chose to respond to OnStateEnter and OnStateExit. These can then raise an event. The final step is to have a StateManager than can subscribe to these events and do some actual work.
Now we have a working Finite State Machine. Ideally put the specific work into the specific State Behaviour and that should mitigate the need for ugly switch statements.