State Machines

Daniel Ercilio Del Rosario Guerra
4 min readJun 20, 2022

--

A state machine is a mathematical abstraction used to design algorithms. A state machine reads a set of inputs and changes to a different state based on those inputs. A state is a description of the status of a system waiting to execute a transition.

This conveniant method allow us to have more control on entities in our games. And most importantly, it allow us to have clean code!

BOOLEAN HELL

I’m going to talk from my experience here. Remember when you had to define some character’s jump?… well, I’m 99.99% sure you used boolean variables to know when your character is jumping/running/Wall Climbing… etc. which land us to have a bunch of boolean variables in our code and making it look like a spaghetti 😨

CREATING OUR STATE MACHINE CLASS

NOTE: Do not forget to add the System.Linq library.

We’re using a generic class for our state machine to pass the type to every single state class.

In both, SetState and AddState methods we force the class to only add states from the derived owner. For example, if we create a state machine for the player, we can only add/set player state classes. But how do we do that?

CREATING THE STATE CLASS

By adding the generic attribute to our states we can specify which class to reference inside the OnUpdate, OnExit, OnEnter methods.

ONE LAST THING… LET’S CREATE AN INTERFACE

Everytime we want to implement a state machine in a class we just have to add this interface.

BUT… DANI… WHAT’S ALL THIS?

Be quiet. We’ve just create the base to implement state machines in our project, let’s go ahead and create a Player.cs and PlayerIdleState.cs scripts.

THE PLAYER COMPONENT

In our player script we define our player states in the awake method and then we set the IdleState as the initial state.

Then, in the update method we run OnUpdate which is just a method debugging a message on console. But, in more realistic scenarios we’re gonna be handling player input to switch between states like: Jump, Idle, Walk… etc.

IDLE STATE

We create a class representing Player’s idle state wich derives from STATE, we have to specify it’s generic value to manipulate the owner’s data. (in this case the player)

NOW, GO BACK TO UNITY

1 — Create an empty scene.

2 — Attach the player component to an empty object.

3 — Run the scene.

You’ll see that our console is showing up the message we just putted in the PlayerIdleState Class.

Conclusion

Finite State Machines is a pretty common pattern in the IT industry, not only on games which allows us to have a better readable code and helps us to organize our projects in a clean way. Let’s not forget, that, implementing changes in this kind of code will be easier than having hundreds of boolean variables to define entity’s states.

--

--

No responses yet