Bird
Raised Fist0
Unityframework~8 mins

Enemy patrol and chase patterns in Unity - Performance & Optimization

Choose your learning style10 modes available
Performance: Enemy patrol and chase patterns
MEDIUM IMPACT
This concept affects frame rate and responsiveness during gameplay by controlling how often enemy AI updates and moves.
Implementing enemy patrol and chase behavior in a game
Unity
void Update() {
  if (Vector3.Distance(transform.position, player.position) < chaseRange) {
    Vector3 direction = player.position - transform.position;
    transform.position += direction.normalized * speed * Time.deltaTime;
  } else {
    Patrol();
  }
}

void Patrol() {
  // Move between waypoints with less frequent updates
}
Only calculates chase movement when player is close, reducing unnecessary calculations.
📈 Performance GainReduces CPU usage by limiting chase logic to relevant frames, improving frame rate stability.
Implementing enemy patrol and chase behavior in a game
Unity
void Update() {
  Vector3 direction = player.position - transform.position;
  transform.position += direction.normalized * speed * Time.deltaTime;
  // No checks, runs every frame
}
Calculating chase direction and moving enemy every frame without conditions causes unnecessary CPU usage.
📉 Performance CostTriggers continuous CPU usage every frame, increasing frame time and risking frame drops.
Performance Comparison
PatternCPU UsageUpdate FrequencyFrame ImpactVerdict
Unconditional chase every frameHighEvery frameCauses frame drops[X] Bad
Conditional chase with distance checkLow to MediumOnly when player nearSmooth frame rate[OK] Good
Rendering Pipeline
Enemy patrol and chase logic runs on the CPU and affects the game loop update frequency, indirectly influencing frame rendering smoothness.
→Game Logic Update
→Physics Calculation
→Frame Rendering
⚠️ BottleneckGame Logic Update stage due to frequent position calculations and AI decisions.
Optimization Tips
1Avoid running enemy AI calculations every frame without conditions.
2Use distance checks to limit chase logic to relevant situations.
3Optimize patrol paths and update frequency to reduce CPU load.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a main performance issue with running enemy chase logic every frame without conditions?
AIt causes unnecessary CPU usage and can lower frame rate.
BIt improves AI responsiveness significantly.
CIt reduces memory usage.
DIt increases GPU load.
DevTools: Unity Profiler
How to check: Open Unity Profiler, run the game, and observe CPU usage and frame time during enemy patrol and chase.
What to look for: Look for spikes in CPU usage and frame time when enemies chase; consistent low CPU usage indicates good performance.

Practice

(1/5)
1. What is the main purpose of an enemy patrol pattern in Unity game development?
easy
A. To make the enemy jump randomly
B. To move the enemy between set points repeatedly
C. To make the enemy disappear and reappear
D. To make the enemy shoot projectiles continuously

Solution

  1. Step 1: Understand enemy patrol behavior

    Enemy patrol means moving the enemy between fixed points in a loop to simulate guarding or searching.
  2. Step 2: Identify correct behavior from options

    Only moving between set points repeatedly matches patrol behavior.
  3. Final Answer:

    To move the enemy between set points repeatedly -> Option B
  4. Quick Check:

    Enemy patrol = moving between points [OK]
Hint: Patrol means looping between points, not random actions [OK]
Common Mistakes:
  • Confusing patrol with attack or random movement
  • Thinking patrol involves shooting or disappearing
2. Which of the following is the correct way to check the distance between the enemy and player in Unity C#?
easy
A. float dist = enemy.position.Distance(player.position);
B. float dist = enemy.position - player.position;
C. float dist = Vector3.Distance(enemy, player);
D. float dist = Vector3.Distance(enemy.position, player.position);

Solution

  1. Step 1: Recall Vector3.Distance syntax

    The correct method to get distance between two Vector3 points is Vector3.Distance(point1, point2).
  2. Step 2: Check each option

    float dist = Vector3.Distance(enemy.position, player.position); uses Vector3.Distance with positions, which is correct. Others have syntax errors or wrong usage.
  3. Final Answer:

    float dist = Vector3.Distance(enemy.position, player.position); -> Option D
  4. Quick Check:

    Use Vector3.Distance(point1, point2) for distance [OK]
Hint: Use Vector3.Distance with positions, not subtract vectors directly [OK]
Common Mistakes:
  • Subtracting vectors without calling Distance method
  • Calling Distance on a Vector3 instance incorrectly
  • Passing transforms instead of positions
3. Given this code snippet for enemy chase, what will be the output if the player is 3 units away and chaseDistance is 5?
if (Vector3.Distance(transform.position, player.position) < chaseDistance) {
    Debug.Log("Chasing player");
} else {
    Debug.Log("Patrolling");
}
medium
A. No output
B. Patrolling
C. Chasing player
D. Error at runtime

Solution

  1. Step 1: Calculate distance and compare

    Distance is 3, chaseDistance is 5, so 3 < 5 is true.
  2. Step 2: Determine which branch runs

    Since condition is true, "Chasing player" is printed.
  3. Final Answer:

    Chasing player -> Option C
  4. Quick Check:

    Distance 3 < 5 triggers chase [OK]
Hint: Compare distance to chaseDistance to decide behavior [OK]
Common Mistakes:
  • Confusing less than with greater than
  • Assuming no output if condition true
  • Thinking code causes error
4. Identify the error in this patrol code snippet:
void Patrol() {
    int currentPoint = 0;
    transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPoint].position, speed * Time.deltaTime);
    if (transform.position == patrolPoints[currentPoint].position) {
        currentPoint++;
        if (currentPoint >= patrolPoints.Length) {
            currentPoint = 0;
        }
    }
}
medium
A. currentPoint should be declared outside the method to keep its value
B. Vector3.MoveTowards is used incorrectly
C. Time.deltaTime should not be multiplied by speed
D. The if condition should use < instead of >

Solution

  1. Step 1: Check variable scope for currentPoint

    currentPoint is reset to 0 every time Patrol() runs, so it never increments properly.
  2. Step 2: Understand how to fix the scope issue

    Declaring currentPoint outside the method (as a class variable) preserves its value between calls.
  3. Final Answer:

    currentPoint should be declared outside the method to keep its value -> Option A
  4. Quick Check:

    Keep patrol index outside method to track progress [OK]
Hint: Keep patrol index as a class variable, not local [OK]
Common Mistakes:
  • Thinking MoveTowards usage is wrong
  • Confusing comparison operators in if
  • Misunderstanding Time.deltaTime usage
5. How can you combine patrol and chase behaviors so the enemy patrols until the player is within 4 units, then chases the player, and returns to patrol if the player moves away?
hard
A. Use a state variable to switch between patrol and chase based on distance checks
B. Call Patrol() and Chase() methods simultaneously every frame
C. Only use Chase() method and ignore patrol points
D. Use a timer to switch behaviors every 5 seconds regardless of player position

Solution

  1. Step 1: Understand behavior switching logic

    The enemy needs to switch between patrol and chase based on player distance dynamically.
  2. Step 2: Use a state variable to track current behavior

    A state variable (like enum or bool) can control which method runs each frame depending on distance.
  3. Step 3: Implement distance check to update state

    If player is closer than 4 units, set state to chase; else set to patrol.
  4. Final Answer:

    Use a state variable to switch between patrol and chase based on distance checks -> Option A
  5. Quick Check:

    State variable + distance check = behavior switch [OK]
Hint: Switch states based on distance, don't run both behaviors together [OK]
Common Mistakes:
  • Running patrol and chase at the same time causing conflicts
  • Ignoring player distance for switching
  • Using timers instead of distance checks
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