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

Creating Dynamic Obstacles with NavMeshObstacle Components

You will place dynamic obstacles that carve holes in the NavMesh, forcing agents to recalculate paths around moving objects.

Creating Dynamic Obstacles with NavMeshObstacle Components

In this lesson, you will learn how to force your NavMeshAgent to navigate around moving objects by using the NavMeshObstacle component to carve real-time holes in your baked navigation mesh.

The Problem with Static Baking

When you bake a NavMesh in the navigation window, the walkable area is calculated based on static colliders. If you move a table or a crate during gameplay, the agent won't "see" it because the navigation mesh remains fixed to the original bake. To solve this, we use the NavMeshObstacle component.

Carving the NavMesh

Unlike a simple collider, the NavMeshObstacle component communicates directly with the NavMesh system. When you enable the Carving checkbox on this component, the obstacle tells the NavMesh to recalculate the walkable area around its current position.

Here is how you typically set this up via script:

using UnityEngine;
using UnityEngine.AI;

public class DynamicGate : MonoBehaviour
{
    private NavMeshObstacle obstacle;

    void Awake()
    {
        obstacle = GetComponent<NavMeshObstacle>();
        // Ensure carving is enabled so the agent recalculates its path
        obstacle.carving = true;
    }
}

Performance Considerations

While "Carving" is powerful, it is computationally expensive because it forces the NavMesh to re-triangulate locally. If you have fifty objects all carving at once, you will notice a significant frame rate drop. To optimize this:

  1. Move, then Carve: Only enable carving while the object is stationary, or use a short delay after the object stops moving.
  2. Bounds: Keep the obstacle's shape as simple as possible (using a Box or Capsule collider shape) to make the geometry calculation easier for the engine.
  3. Move Threshold: Adjust the Carve Move Threshold in the component settings; this prevents the mesh from recalculating if the object has only moved a tiny, negligible distance.

By strategically enabling carving, you allow your agents to dynamically adapt to a changing environment without having to rebake the entire level at runtime.

Key Takeaway: Enable the "Carving" property on a NavMeshObstacle to force agents to treat moving objects as walkable-area holes, but manage this feature carefully to avoid performance hits during frequent updates.