isChasing, isAttacking, isStunned, and then I spent an hour figuring out why an enemy is somehow doing all three at once! I figured out a much more efficient way of making enemies behave the way I wanted to later on. The discovery of FSM, or Finite State Machines! In this article, I'll go over what it is and the best way to implement it. And of course, the when, where, and how.Let's untangle this one!
Why Booleans Break Your Code
Like I said earlier, in the beginning, when I first started making a state machine (Udemy Zombie game tutorial), I used a boolean for pretty much everything, and an if chain to sort it out:
void Update()
{
if (isDead) { return; }
if (isStunned)
{
// do nothing
}
else if (isAttacking)
{
// attack logic
}
else if (isChasing)
{
// chase logic
}
else if (playerInRange && !isPatrolling)
{
isChasing = true; // but should isPatrolling switch off? who knows
}
}
At the time, it made sense in my mind, but it works for about a day. Then you add a "fleeing" behavior, and suddenly every boolean has to know about every other boolean. Two of them can be true at once, and nothing in the code says that shouldn't happen. It gets way too complicated! There's a cleaner way of going about doing this.
What Is A State Machine In Unity?
Now, let's first answer this question. A state machine is a system that is always in exactly one state at a time, with clear rules for moving from one state to another. That's the whole idea behind it. Instead of five booleans that might contradict each other, you have one variable that says what the enemy is doing right now. A state of mind, if you will.
Every state machine has three parts:
- States - the things the object can be doing, like Idle, Chase, and Attack
- Transitions - the rules for switching, like "if the player gets within range, go from Idle to Chase"
- The current state - exactly one, at any moment
Because only one state is active, the "attacking and fleeing at the same time" bug becomes impossible by design.
An Enemy AI State Machine: Idle, Chase, Attack
The simplest enemy AI state machine uses an enumerator (enum), which is a named list of options, plus a switch. Here's a complete one as an example:
public class Enemy : MonoBehaviour
{
private enum State { Idle, Chase, Attack }
[SerializeField] private State state = State.Idle;
[SerializeField] private Transform player;
[SerializeField] private float chaseRange = 10f;
[SerializeField] private float attackRange = 2f;
[SerializeField] private float moveSpeed = 3f;
void Update()
{
float distance = Vector3.Distance(transform.position, player.position);
switch (state)
{
case State.Idle:
if (distance < chaseRange)
{
state = State.Chase;
}
break;
case State.Chase:
transform.position = Vector3.MoveTowards(
transform.position, player.position, moveSpeed * Time.deltaTime);
if (distance < attackRange)
{
state = State.Attack;
}
else if (distance > chaseRange)
{
state = State.Idle;
}
break;
case State.Attack:
Debug.Log("Attacking!");
if (distance > attackRange)
{
state = State.Chase;
}
break;
}
}
}
Each case handles one state, and each state decides when to hand off to the next. As a bonus, because state is a serialized field, the Inspector shows a dropdown of the current state while the game runs. That's a free debugging window.
This is plenty for a small enemy. The trouble starts when you have eight states, and every one needs setup code when it begins and cleanup code when it ends. That giant switch turns into the boolean soup all over again.
Building A Finite State Machine In C#
For bigger jobs, you give each state its own class. This is a proper finite state machine in C#, "finite" simply meaning there's a fixed, known list of states. Every state gets three methods: one that runs when you enter it, one that runs every frame, and one that runs when you leave.
public interface IState
{
void Enter();
void Tick();
void Exit();
}
public class StateMachine
{
private IState currentState;
public void ChangeState(IState newState)
{
currentState?.Exit();
currentState = newState;
currentState.Enter();
}
public void Tick()
{
currentState?.Tick();
}
}
The whole machine is those few lines. ChangeState shuts down the old state, switches, and starts the new one, so cleanup and setup always happen in the right order. Now each state becomes a small, focused class:
public class ChaseState : IState
{
private readonly Enemy enemy;
public ChaseState(Enemy enemy)
{
this.enemy = enemy;
}
public void Enter()
{
Debug.Log("Started chasing");
}
public void Tick()
{
enemy.MoveTowardsPlayer();
if (enemy.DistanceToPlayer < enemy.AttackRange)
{
enemy.StateMachine.ChangeState(enemy.AttackState);
}
}
public void Exit()
{
Debug.Log("Stopped chasing");
}
}
Finally, the enemy creates its states once and hands control to the machine. Write IdleState and AttackState the same way as ChaseState:
public class Enemy : MonoBehaviour
{
[SerializeField] private Transform player;
[SerializeField] private float attackRange = 2f;
[SerializeField] private float moveSpeed = 3f;
public StateMachine StateMachine { get; private set; }
public IdleState IdleState { get; private set; }
public ChaseState ChaseState { get; private set; }
public AttackState AttackState { get; private set; }
public float AttackRange => attackRange;
public float DistanceToPlayer => Vector3.Distance(transform.position, player.position);
void Awake()
{
StateMachine = new StateMachine();
IdleState = new IdleState(this);
ChaseState = new ChaseState(this);
AttackState = new AttackState(this);
}
void Start()
{
StateMachine.ChangeState(IdleState);
}
void Update()
{
StateMachine.Tick();
}
public void MoveTowardsPlayer()
{
transform.position = Vector3.MoveTowards(
transform.position, player.position, moveSpeed * Time.deltaTime);
}
}
Notice the states are created once in Awake and reused. Creating a brand new state object on every transition would feed the garbage collector for no good reason.
State Machine Common Mistakes
A few things trip people up:
- Forgetting the starting state. If you never call
ChangeStateonce, the machine has no current state and does nothing. - Skipping cleanup in
Exit. If a state starts a sound, a timer, or a coroutine, stop it on the way out. - Scattering transitions everywhere. Keep each transition inside the state it leaves from, so you can read a state and know where it leads.
- State explosion. If you hit fifteen states with transitions everywhere, it's time to look at behavior trees, a heavier tool for complex AI.
- Hard-to-see bugs. Log every
EnterandExit, and you'll see exactly what the machine is doing.
What About The Animator?
If you've opened Unity's Animator window, you've already seen a state machine. It has states, transitions, and arrows, exactly like the ones above, but it's built for animation. It's a different tool, and the two work well together: your AI states can set Animator parameters to play the right animation for whatever the enemy is doing.
So Which Approach Should You Actually Use?
Here's the no-fluff version, the gut check you can run through in your head:
- Two simple behaviors, and it'll stay that way → a boolean is fine
- Three to six states with small amounts of logic → an enum and a
switch, the simplest enemy AI state machine - States that need setup and cleanup, or more than six of them → a class-based finite state machine in C#
- Complicated AI with lots of conditions → look at behavior trees
- Animation states → the Animator
- Not sure → ask "is this thing always doing exactly one of several things?" If yes, build a state machine in Unity
Start simple. An enum and a switch will carry you further than you'd think, and moving to classes later is an easy upgrade once the code starts to hurt.
There are actually more advanced state machine options in Unity, like the Unity Behavior and hierarchical state machine in plain C# Package, which implement child state machines. But this really goes beyond the scope of this article and is more suited for a separate article (Unity expert), which I will elaborate on later. For a more basic to intermediate project, you should be able to get away with the information in this topic.
Wrapping Up
A state machine in Unity swaps a web of booleans for one clear question: what is this object doing right now? Define the states, write down the transitions, and let only one be active at a time. Your enemies will behave more predictably, your bugs will be easier to find, and adding a new behavior will stop feeling like defusing a bomb.
~happy Coding!


No comments:
Post a Comment