Finite state machines are one of the most popular patterns in game development for good reason. They can reduce complexity and create more readable programs by encouraging modular, re-usable states. While FSMs (finite state machines) fail to scale to more complex situations, they’re excellent solutions for most common-place situations like dealing with application state or making simple AI.*

*I won’t explain the basic concepts and use-cases of FSMs because I think there are already a lot of good articles online like this article from Bob Nystrom’s book on game programming patterns.

There are two main approaches for creating and using FSMs: writing a quick and dirty implementation or buying an asset from the asset store to use. But there is a third option: using Unity’s built-in animator system (Mecanim).

Why would you use Unity’s animation system?

It can seem a bit weird to reuse the animation system to create finite state machines, but the animator is a finite state machine. While it has animation specific features that can get in the way, the animator system does almost everything you’d want. It comes with tools for editing and visualizing the state machine during run-time. Also, it’s supported by Unity, tested by millions of developers, and any Unity animation experience you already have is applicable.

Why not build a quick and dirty implementation instead?

A quick and dirty implementation works well for the task that it’s designed for, but once you need to use this pattern elsewhere, you’ll find yourself re-writing the same code over and over again. The animator system can easily create different state machines with re-usable state behaviors.

Then how about using a third-party asset?

There are third-party assets that rival the animator system in complexity and power (like NodeCanvas). They also have the advantage of a cleaner API because they don’t deal with animations. I’ve even built my own implementation that I eventually stopped using in favor of re-repurposing the animator. Because you’re going to using the animator to, well, animate, re-using it for state-machines means you don’t have to switch contexts between two similar systems.