📖 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
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.