Bird
Raised Fist0
Unityframework~30 mins

State machines for AI behavior in Unity - Mini Project: Build & Apply

Choose your learning style10 modes available
State machines for AI behavior
📖 Scenario: You are creating a simple AI for a game character in Unity. This AI will have three states: Idle, Patrol, and Chase. The character will start by idling, then patrol between points, and chase the player if the player is close enough.
🎯 Goal: Build a basic state machine in Unity C# script to control AI behavior switching between Idle, Patrol, and Chase states based on player distance.
📋 What You'll Learn
Create an enum called AIState with values Idle, Patrol, and Chase
Create a variable called currentState of type AIState and set it to AIState.Idle
Create a float variable called chaseDistance and set it to 5f
Write a method called UpdateState that changes currentState to Chase if the player is within chaseDistance, otherwise to Patrol
Print the current state in the Update method
💡 Why This Matters
🌍 Real World
State machines are used in games to control AI characters' behavior in a clear and organized way.
💼 Career
Understanding state machines is important for game developers and AI programmers to create responsive and maintainable AI systems.
Progress0 / 4 steps
1
Create AIState enum and currentState variable
Create an enum called AIState with values Idle, Patrol, and Chase. Then create a variable called currentState of type AIState and set it to AIState.Idle inside the AIBehavior class.
Unity
Hint

Use enum AIState { Idle, Patrol, Chase } and declare public AIState currentState = AIState.Idle; inside the class.

2
Add chaseDistance variable
Add a public float variable called chaseDistance and set it to 5f inside the AIBehavior class.
Unity
Hint

Declare public float chaseDistance = 5f; inside the class.

3
Write UpdateState method to change currentState
Write a public method called UpdateState that takes a float parameter called playerDistance. Inside this method, if playerDistance is less than or equal to chaseDistance, set currentState to AIState.Chase. Otherwise, set currentState to AIState.Patrol.
Unity
Hint

Use an if statement to compare playerDistance with chaseDistance and set currentState accordingly.

4
Print currentState in Update method
In the Update method, call UpdateState with a test float value of 3f to simulate player distance. Then print the current state using Debug.Log with the message "Current State: " followed by currentState.
Unity
Hint

Call UpdateState(3f) inside Update() and print the current state with Debug.Log("Current State: " + currentState);.

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