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

Implementing NavMeshObstacles for Dynamic Environment Changes

Master the use of NavMeshObstacles to dynamically carve the navigation surface without triggering expensive full-scene rebakes during runtime.

In this lesson, you will learn how to use NavMeshObstacle components to dynamically cut holes into your navigation surface, allowing AI agents to navigate around moving objects without needing to rebake the entire scene.

The Problem with Static NavMeshes

Normally, your NavMesh is a static, pre-baked map. If a door closes or a crate is pushed into a hallway, an AI agent will treat that space as walkable because the original bake didn't account for the new object. You could perform a full NavMesh rebake at runtime, but that is extremely expensive and will cause significant performance spikes, especially in complex environments.

The Solution: Carving

The NavMeshObstacle component is designed to solve this by "carving" a hole into the existing navigation surface at runtime. When you add a NavMeshObstacle to a GameObject and check the Carve box, Unity intelligently updates the local area of the NavMesh.

Rather than recalculating the entire mesh, the system performs a localized operation. This is efficient enough to handle objects like closing blast doors, fallen debris, or temporary barricades.

Implementation Example

To implement this, ensure your object has a NavMeshObstacle component. You can toggle the carving behavior via script when an event occurs:

using UnityEngine;
using UnityEngine.AI;

public class DynamicDoor : MonoBehaviour
{
    private NavMeshObstacle obstacle;

    void Start()
    {
        obstacle = GetComponent<NavMeshObstacle>();
    }

    public void CloseDoor()
    {
        // Enabling Carve creates a hole in the NavMesh at this location
        obstacle.carving = true;
    }

    public void OpenDoor()
    {
        // Disabling Carve restores the walkable path
        obstacle.carving = false;
    }
}

When carving is enabled, the AI’s pathfinding algorithm will perceive the obstacle’s bounds as non-walkable terrain. Because this only affects the immediate area, your AI remains responsive to environmental changes without stalling the frame rate. Remember to adjust the Carving Move Threshold if you have slow-moving objects, as this determines how far an object must move before the NavMesh is updated again.

Key Takeaway: Use NavMeshObstacles with the 'Carve' setting enabled to dynamically update navigation paths locally, keeping your performance high by avoiding expensive global NavMesh rebakes.