State machines help AI decide what to do next by organizing actions into clear steps. They make AI behavior easy to understand and control.
When you want a game character to switch between walking, running, and attacking.
When an enemy needs to patrol, chase the player, or hide.
When you want to control a robot's tasks like searching, picking up items, and returning.
When you want to make sure AI only does one action at a time and changes smoothly.
When you want to avoid confusing or random AI behavior.
Syntax
Unity
public enum State {
Idle,
Patrol,
Chase,
Attack
}
public State currentState;
void Update() {
switch (currentState) {
case State.Idle:
// do idle stuff
break;
case State.Patrol:
// do patrol stuff
break;
case State.Chase:
// do chase stuff
break;
case State.Attack:
// do attack stuff
break;
}
}
Use enums to list all possible states clearly.
Use a switch or if-else to decide what to do based on the current state.
Examples
This example shows how to define states and set the starting state.
Unity
public enum State { Idle, Walk, Run }
public State currentState = State.Idle;
Using if-else to handle different states in the update loop.
Using switch-case to print messages based on the current state.
Unity
switch (currentState) {
case State.Idle:
Debug.Log("Standing still");
break;
case State.Walk:
Debug.Log("Walking around");
break;
case State.Run:
Debug.Log("Running fast");
break;
}
Sample Program
This program shows a simple AI that starts idle. If the player gets close, it switches to chase. If the player moves away, it goes back to idle.
Unity
using UnityEngine;
public class SimpleAI : MonoBehaviour {
public enum State {
Idle,
Patrol,
Chase
}
public State currentState = State.Idle;
public Transform player;
public float chaseDistance = 5f;
void Update() {
switch (currentState) {
case State.Idle:
Debug.Log("AI is idle.");
if (Vector3.Distance(transform.position, player.position) < chaseDistance) {
currentState = State.Chase;
}
break;
case State.Patrol:
Debug.Log("AI is patrolling.");
// Patrol logic here
break;
case State.Chase:
Debug.Log("AI is chasing the player!");
// Chase logic here
if (Vector3.Distance(transform.position, player.position) > chaseDistance) {
currentState = State.Idle;
}
break;
}
}
}
OutputSuccess
Important Notes
Keep states simple and clear to avoid confusion.
Use distances or events to switch between states smoothly.
Debug.Log helps you see what the AI is doing while testing.
Summary
State machines organize AI actions into clear steps.
Use enums and switch or if-else to control AI behavior.
Switch states based on conditions like player distance or timers.
Practice
(1/5)
1. What is the main purpose of using a state machine in AI behavior in Unity?
easy
A. To store player preferences
B. To increase the frame rate of the game
C. To create 3D models automatically
D. To organize AI actions into clear, manageable states
Solution
Step 1: Understand AI behavior organization
State machines help break down AI actions into distinct states like Idle, Patrol, or Attack.
Step 2: Identify the main benefit
This organization makes AI easier to manage and debug.
Final Answer:
To organize AI actions into clear, manageable states -> Option D
Quick Check:
State machines = organized AI behavior [OK]
Hint: State machines = clear AI steps, not performance boosts [OK]
Common Mistakes:
Confusing state machines with performance optimization
Thinking state machines store player data
Assuming state machines create graphics
2. Which of the following is the correct way to define an enum for AI states in Unity C#?
easy
A. enum AIState { Idle, Patrol, Attack }
B. enum AIState = { Idle, Patrol, Attack }
C. enum AIState: int { Idle, Patrol, Attack }
D. enum AIState() { Idle, Patrol, Attack }
Solution
Step 1: Recall enum syntax in C#
Enums are declared with the keyword 'enum' followed by the name and curly braces listing values.
Step 2: Check each option
enum AIState { Idle, Patrol, Attack } uses correct syntax: no equals sign or parentheses, just braces and values.
B. Missing break after setting currentState to Patrol
C. Update method should return a value
D. Debug.Log cannot be used inside switch
Solution
Step 1: Check switch cases for breaks
The Idle case sets currentState to Patrol but lacks a break statement.
Step 2: Understand effect of missing break
Without break, code falls through to Patrol case, causing both logs to print unexpectedly.
Final Answer:
Missing break after setting currentState to Patrol -> Option B
Quick Check:
Missing break causes fall-through [OK]
Hint: Always add break after each case to avoid fall-through [OK]
Common Mistakes:
Thinking enum syntax is wrong
Expecting Update to return a value
Believing Debug.Log is invalid in switch
5. You want an AI to switch from Patrol to Attack only if the player is within 2 units and the AI's health is above 50. Which condition correctly implements this in the state machine update?
hard
A. if (playerDistance <= 2 && health > 50) currentState = AIState.Attack;
B. if (playerDistance > 2 || health <= 50) currentState = AIState.Attack;
C. if (playerDistance <= 2 || health > 50) currentState = AIState.Attack;
D. if (playerDistance >= 2 && health < 50) currentState = AIState.Attack;
Solution
Step 1: Translate requirements to conditions
AI attacks only if playerDistance is 2 or less AND health is above 50.
Step 2: Match condition with options
if (playerDistance <= 2 && health > 50) currentState = AIState.Attack; uses '&&' (AND) with correct comparisons: playerDistance <= 2 and health > 50.
Final Answer:
if (playerDistance <= 2 && health > 50) currentState = AIState.Attack; -> Option A
Quick Check:
Both conditions must be true for attack [OK]
Hint: Use && for both conditions to be true [OK]
Common Mistakes:
Using || instead of &&
Reversing comparison operators
Confusing greater than and less than
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.