Lesson 88 +10 XP

NavMesh and AI Navigation

NavMesh and AI Navigation

Unity's NavMesh system allows GameObjects to intelligently navigate around 3D environments. It works by baking a navigation mesh from your scene geometry.

Core Concepts

  • NavMesh: A data structure that describes walkable surfaces in your scene.
  • NavMeshAgent: A component that moves a GameObject along the NavMesh towards a destination.
  • NavMeshObstacle: Marks moving objects (like crates) as obstacles that agents must avoid.
  • Off-Mesh Links: Manual connections between otherwise disconnected NavMesh areas (e.g., jumping over a gap).

Baking a NavMesh

  1. Mark static geometry as Navigation Static in the Inspector.
  2. Open Window > AI > Navigation (or Window > AI > Navigation (Obsolete) for older versions).
  3. In the Bake tab, configure agent radius, height, and max slope.
  4. Click Bake. Unity creates the NavMesh data and saves it with the scene.

NavMeshAgent Component

Add NavMeshAgent to any GameObject you want to pathfind. Key properties:

  • Speed: Maximum movement speed.
  • Angular Speed: Rotation speed when turning.
  • Stopping Distance: How close to the target the agent stops.
  • Radius / Height: Capsule used to check walkable space.

Scripting an Agent

using UnityEngine;
using UnityEngine.AI;

public class EnemyChaser : MonoBehaviour
{
    private NavMeshAgent _agent;
    private Transform _player;

    void Start()
    {
        _agent = GetComponent<NavMeshAgent>();
        _player = GameObject.FindWithTag("Player").transform;
    }

    void Update()
    {
        // Continuously update the destination
        _agent.SetDestination(_player.position);
    }
}

Checking if the Agent Reached its Destination

bool HasArrived()
{
    // Check the remaining path distance, but only when a path is calculated
    return !_agent.pathPending
        && _agent.remainingDistance <= _agent.stoppingDistance
        && (!_agent.hasPath || _agent.velocity.sqrMagnitude == 0f);
}

NavMesh Areas and Costs

You can define multiple NavMesh areas (e.g., Road, Grass, Water) with different costs. Agents will prefer cheaper paths. This is configured in the Navigation window's Areas tab.

// Set area costs at runtime
NavMesh.SetAreaCost(NavMesh.GetAreaFromName("Water"), 5f);

TL;DR

  • Bake a NavMesh from static geometry via Window > AI > Navigation.
  • Add a NavMeshAgent component to moving GameObjects, then call SetDestination().
  • Use remainingDistance and stoppingDistance to detect arrival.
  • NavMesh areas with costs allow agents to prefer certain terrain types.