Course contentsShow
← Unity Game Development
Lesson 547 of 8288. Artificial IntelligenceFree lesson

Optimizing Perception Updates with Coroutines

You will implement time-sliced sensory checks to maintain high performance when managing multiple AI agents in a complex scene.

In this lesson, you will learn how to distribute high-cost sensory calculations across multiple frames using coroutines to prevent frame rate drops when managing many AI agents.

The Problem with "Every-Frame" Perception

When you have dozens of NPCs performing complex line-of-sight or spatial queries every single frame, your CPU usage spikes. If every agent executes a Physics.Raycast or a distance check in Update(), the main thread becomes bottlenecked, leading to "stuttering." Instead of checking every agent at once, we use time-slicing.

Implementing Time-Slicing with Coroutines

By using a coroutine, we can pause the perception check and resume it later, or stagger the checks across several frames so that only a fraction of your agents are "thinking" at any given moment.

Here is how you can implement a basic staggered perception loop:

private IEnumerator PerceptionRoutine()
{
    // Define a wait interval to spread out processing
    WaitForSeconds wait = new WaitForSeconds(0.2f);

    while (true)
    {
        // Only check visibility if the agent is active
        if (gameObject.activeInHierarchy)
        {
            PerformComplexSensoryCheck();
        }

        // Yield control back to Unity, effectively throttling the update frequency
        yield return wait;
    }
}

Why This Matters

By utilizing yield return, you decouple your AI's reaction time from the engine's frame rate. Even better, you can introduce a random offset (Random.Range(0, 0.2f)) before starting the coroutine for each agent. This ensures that your agents don't all perform their perception calculations at the exact same moment, smoothing out your performance profile significantly.

Rather than forcing 50 NPCs to calculate their field of view on the same frame, you distribute that computational load across a wider window of time. The player will never notice a 200ms delay in an NPC's "reaction" to being seen, but they will certainly notice if your game drops from 60 FPS to 20 FPS because of redundant sensory updates.

Key Takeaway: Use coroutines with staggered delays to distribute intensive sensory logic across time, preventing CPU spikes and maintaining consistent frame rates in high-density AI scenes.