Bird
Raised Fist0
Unityframework~10 mins

State machines for AI behavior in Unity - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - State machines for AI behavior
Start AI
↓
Check Current State
↓
Execute State Behavior
↓
Check Transition Conditions
↓
Change State
↓
Loop Back to Check Current State
The AI starts, checks its current state, runs that state's behavior, then checks if it should switch states based on conditions, looping continuously.
Execution Sample
Unity
enum State { Idle, Patrol, Chase }
State currentState = State.Idle;

void Update() {
  switch(currentState) {
    case State.Idle: /* wait */ break;
    case State.Patrol: /* move around */ break;
    case State.Chase: /* follow player */ break;
  }
  // Check transitions
}
This code shows a simple AI with three states and how it runs behavior based on the current state each frame.
Execution Table
StepCurrent StateCondition CheckedCondition ResultAction TakenNext State
1IdlePlayer detected?NoIdle behavior (wait)Idle
2IdlePlayer detected?YesSwitch to ChaseChase
3ChasePlayer lost?NoChase behavior (follow player)Chase
4ChasePlayer lost?YesSwitch to PatrolPatrol
5PatrolPlayer detected?NoPatrol behavior (move around)Patrol
6PatrolPlayer detected?YesSwitch to ChaseChase
7ChasePlayer lost?NoChase behavior (follow player)Chase
ExitChaseGame ends or AI disabled-Stop AI-
💡 AI stops when game ends or AI is disabled
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6After Step 7Final
currentStateIdleIdleChaseChasePatrolPatrolChaseChase-
Key Moments - 3 Insights
Why does the AI stay in the same state sometimes instead of switching?
Because the condition to switch states is false (see steps 1, 3, and 5 in the execution_table where the condition result is No, so the AI continues current behavior).
How does the AI decide which state to switch to?
It checks specific conditions for each state (like 'Player detected?' or 'Player lost?') and switches only if those conditions are true, as shown in steps 2, 4, and 6.
What happens if no conditions are met to change state?
The AI keeps executing the behavior of the current state, looping back to check conditions again next update (see steps with 'No' condition results).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2. What is the AI's current state after this step?
AChase
BIdle
CPatrol
DStopped
💡 Hint
Check the 'Next State' column for step 2 in the execution_table.
At which step does the AI switch from Chase to Patrol?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look for the row where 'Current State' is Chase and 'Next State' is Patrol.
If the condition 'Player detected?' is always No, what state will the AI stay in according to variable_tracker?
AChase
BIdle
CPatrol
DStops immediately
💡 Hint
See variable_tracker where currentState stays Idle when 'Player detected?' is No.
Concept Snapshot
State machines control AI by defining states and transitions.
Each update, AI runs current state behavior.
Then it checks conditions to switch states.
If condition true, AI changes state; else stays.
This loop repeats, making AI react simply and clearly.
Full Transcript
This visual execution shows how a simple AI uses a state machine to decide what to do. The AI starts in an Idle state, waits, and checks if the player is detected. If yes, it switches to Chase state to follow the player. If the player is lost, it switches to Patrol state to move around. Each step shows the current state, the condition checked, the result, and the next state. Variables track the current state over time. Key moments clarify why the AI sometimes stays in the same state and how it decides to switch. The quiz tests understanding of state changes and conditions. This helps beginners see how state machines make AI behavior organized and easy to follow.

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

  1. Step 1: Understand AI behavior organization

    State machines help break down AI actions into distinct states like Idle, Patrol, or Attack.
  2. Step 2: Identify the main benefit

    This organization makes AI easier to manage and debug.
  3. Final Answer:

    To organize AI actions into clear, manageable states -> Option D
  4. 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

  1. Step 1: Recall enum syntax in C#

    Enums are declared with the keyword 'enum' followed by the name and curly braces listing values.
  2. Step 2: Check each option

    enum AIState { Idle, Patrol, Attack } uses correct syntax: no equals sign or parentheses, just braces and values.
  3. Final Answer:

    enum AIState { Idle, Patrol, Attack } -> Option A
  4. Quick Check:

    Correct enum syntax = enum AIState { Idle, Patrol, Attack } [OK]
Hint: Enums use braces {} without equals or parentheses [OK]
Common Mistakes:
  • Using '=' sign after enum name
  • Adding parentheses after enum name
  • Incorrect colon usage for enum
3. Given this code snippet, what will be printed if currentState is AIState.Patrol and playerDistance is 3?
enum AIState { Idle, Patrol, Attack }
AIState currentState = AIState.Patrol;
float playerDistance = 3f;
switch (currentState) {
  case AIState.Idle:
    Console.WriteLine("Idle");
    break;
  case AIState.Patrol:
    if (playerDistance < 5) Console.WriteLine("Chase");
    else Console.WriteLine("Patrol");
    break;
  case AIState.Attack:
    Console.WriteLine("Attack");
    break;
}
medium
A. Patrol
B. Idle
C. Chase
D. Attack

Solution

  1. Step 1: Identify current state and player distance

    currentState is Patrol and playerDistance is 3 (less than 5).
  2. Step 2: Follow switch logic for Patrol

    Since playerDistance < 5, it prints "Chase".
  3. Final Answer:

    Chase -> Option C
  4. Quick Check:

    Patrol + distance < 5 = Chase [OK]
Hint: Check conditions inside the matching case block [OK]
Common Mistakes:
  • Ignoring the if condition inside Patrol case
  • Confusing playerDistance comparison operator
  • Assuming default case runs
4. Identify the error in this AI state machine update method:
enum AIState { Idle, Patrol, Attack }
AIState currentState = AIState.Idle;
void Update() {
  switch (currentState) {
    case AIState.Idle:
      Debug.Log("Idle");
      currentState = AIState.Patrol;
    case AIState.Patrol:
      Debug.Log("Patrol");
      break;
  }
}
medium
A. Enum declaration is incorrect
B. Missing break after setting currentState to Patrol
C. Update method should return a value
D. Debug.Log cannot be used inside switch

Solution

  1. Step 1: Check switch cases for breaks

    The Idle case sets currentState to Patrol but lacks a break statement.
  2. Step 2: Understand effect of missing break

    Without break, code falls through to Patrol case, causing both logs to print unexpectedly.
  3. Final Answer:

    Missing break after setting currentState to Patrol -> Option B
  4. 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

  1. Step 1: Translate requirements to conditions

    AI attacks only if playerDistance is 2 or less AND health is above 50.
  2. Step 2: Match condition with options

    if (playerDistance <= 2 && health > 50) currentState = AIState.Attack; uses '&&' (AND) with correct comparisons: playerDistance <= 2 and health > 50.
  3. Final Answer:

    if (playerDistance <= 2 && health > 50) currentState = AIState.Attack; -> Option A
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard