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

Optimizing Pathfinding Performance for Large Scenes

You will implement runtime NavMesh baking and agent pathfinding optimizations to ensure smooth performance in expansive, high-density game environments.

In this lesson, you will learn how to maintain high frame rates in expansive, high-density game environments by utilizing asynchronous runtime NavMesh baking and intelligent pathfinding throttling.

The Scaling Challenge

In large scenes, recalculating navigation paths or updating the NavMesh for every object every frame creates massive CPU spikes. If your world is too vast to bake as a single static mesh, or if it changes dynamically, you must move away from "all-at-once" processing. Instead, we divide the work to prevent the main thread from stuttering.

Runtime Baking and Throttling

To optimize, we perform NavMesh Surface updates only when necessary and distribute the load. Instead of triggering a full NavMeshSurface.BuildNavMesh() during gameplay—which stalls the game—we use UpdateNavMesh() to recalculate specific localized areas.

Furthermore, we optimize NavMeshAgent performance by implementing a Pathfinding Throttler. Rather than every agent requesting a new path every frame, we stagger their path requests across different frames.

// Simple throttler for path requests
IEnumerator RequestPathWithDelay(NavMeshAgent agent, Vector3 target) {
    // Only update path for a small subset of agents per frame
    yield return new WaitForSeconds(Random.Range(0.1f, 0.5f));
    if (agent.isActiveAndEnabled) {
        agent.SetDestination(target);
    }
}

Strategic Optimizations

  1. NavMesh Bounds: Use local NavMeshSurface components on specific game zones rather than one global mesh. This allows you to rebuild only the small section of the world that changed (e.g., a door opening or a bridge collapsing) rather than the entire map.
  2. Obstacle Pooling: Use NavMeshObstacle with Carving enabled sparingly. Excessive carving is expensive; ensure Move Threshold is set high enough that small jittery movements don't trigger constant recalculations.
  3. Agent Logic: Set NavMeshAgent.obstacleAvoidanceType to a lower quality setting for background NPCs to save CPU cycles, reserving "High Quality" avoidance only for critical units near the player.

By offloading calculations and staggering agent updates, you ensure that the navigation system scales gracefully with your world size.

Key Takeaway: Optimize your large-scale pathfinding by modularizing your NavMesh surfaces and throttling path requests to prevent CPU-heavy spikes.