FSM in Unity to Create Smart AI

Tyler Smallwood
3 min readJul 17, 2023

--

Objective: Cover setting up a Finite State Machine.

FSM stands for Finite State Machine. FSM allows for AI’s to decide what they will be doing. Got a guard on patrol? See’s the player and now the guard is chasing the player, player got away go back to patrolling. This is how FSM can work, I’ll cover small steps on how to get started with FSM and NavMesh in Unity.

To get started with this, we will use the last article to get started. With the AI script open we will create an enum called AIState. Enums is a data type that can make reading a little easier. Creating an enum is similar to a method but is typically at the top of the script. We set the different enums and separate them with a comma.

We will also need to keep track of the currentState the AI is in. We will create a AIState named currentState.

To change the state we would just need to assign the _currentState to that state. For an example, if we wanted to jump and we hit the e key for jump, just set the state to AIState.Jumping. We also use _navMeshAgent.isStopped to stop moving the AI.

To get different actions from the AI per state we can use a switch statement where we check to see what the _currentState is equal to. For walking we will just calculate the movement based on this Article:

Jumping, and Death are just going to print out their action. Attacking will do something different.

For the Attacking we just check to see if we are attacking and if we are not, set _attacking to true and start a Coroutine that will print that the routine was called, stop the AI movement and wait a few seconds. Than change the state back to walking and allow the AI to move again. Finally change the bool back to false.

This is how a FSM could help in games for Enemy AI’s.

Thank you for reading and have a wonderful day!

--

--

Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer