Finite State Machines In Unity
Finite-state machine - Wikipedia
A finite-state machine ( FSM) or finite-state automaton ( FSA, plural: automata), finite automaton, or simply a state…
A finite-state machine (FSM) is an abstract machine that can be in exactly one of a finite number of states at any given time. The FSM can change from one state to another in response to some inputs; the change from one state to another is called a transition. An FSM is defined by a list of its states, its initial state, and the inputs that trigger each transition.
Simply Put you have a finite number of states that you can be in and you want to transition between them.
FSM’s are useful in a lot of situations, Animations, AI, or Locomotion systems just to name a few.
I am going to Take a look at a Locomotion State.
To define what state I am in I will be using an Enum.
Now I have to take care of the actions.
Now I have to take care calling these methods from the Update Method.
Using Animator Component.
Creating Finite State Machines in Code is not very clean as it can be difficult to follow the transitions from one state to another. Unity has one built in designed for animations but it also works great for creating a FSM.
Animation System Overview
Unity has a rich and sophisticated animation system (sometimes referred to as ‘ Mecanim ‘). It provides: Easy workflow…
The Locomotion FSM can be simplified to just a variable to cache the animator component and an Update Method to pass on the Variables that are used to control the State.
Now on the Unity Side I create an Animator Controller for the FSM and add it to the Game Object.
I Edit the Animator Controller and add the States to it.
I added the Bool Parameters to use for transitioning the States.
I set the transition up in the Animator.
Now It is extremely easy to follow the code and see exactly what is going on. We can even watch it change states in the Animator. It changes states like it is suppose to / Even though my fake gravity causes it to almost instantly return to the grounded state, if you blink you miss it going into the In Air State.
The Code Can be Found on my Git Hub Page