Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท 2D and 3D Workflows

NavMesh and AI Navigation in Unity

Make characters walk around obstacles with Unity's NavMesh - baking, NavMeshAgent, obstacles, off-mesh links - and build simple enemy AI with runnable A-star and state machine stand-ins.

An enemy that walks straight at the player through walls is not much of an enemy. Moving a character around obstacles is called pathfinding, and Unity solves it for 3D worlds with a NavMesh: a simplified map of the surfaces where characters can walk. A NavMeshAgent component then asks "how do I get from here to there?" and moves along the answer.

This lesson explains baking a NavMesh, steering agents, handling obstacles and links, and writing a small enemy brain. Unity is not available here, so the Unity API code is read-only and the algorithms run as C# stand-ins, including the A* search that underlies navigation.

The AI Navigation package

In Unity 6 navigation lives in the AI Navigation package (com.unity.ai.navigation). The workflow:

  1. Add a NavMesh Surface component to the ground object (or an empty object that covers the level). Choose which layers and objects to include and the Agent Type (radius, height, max slope, step height).
  2. Click Bake. Unity voxelizes the geometry, finds walkable areas and builds a polygon mesh, drawn in blue in the Scene view with the Navigation overlay open.
  3. Add a NavMeshAgent to a character. Set speed, acceleration, stopping distance and angular speed.
  4. Call agent.SetDestination(point).
C#
using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class ClickToMove : MonoBehaviour
{
    NavMeshAgent agent;

    void Awake() => agent = GetComponent<NavMeshAgent>();

    void Update()
    {
        if (Input.GetMouseButtonDown(0) &&
            Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit))
        {
            agent.SetDestination(hit.point);
        }
    }

    public bool HasArrived =>
        !agent.pathPending && agent.remainingDistance <= agent.stoppingDistance &&
        (!agent.hasPath || agent.velocity.sqrMagnitude < 0.01f);
}

Checking arrival correctly needs those three conditions, because remainingDistance is not valid while the path is still being computed. Agents avoid each other with local avoidance (set Avoidance Priority so important agents push through).

  • NavMesh Obstacle with Carve ticked cuts a hole in the NavMesh at runtime, so crates and closing doors reshape paths. Moving obstacles without carving just get avoided locally.
  • Areas (Water, Road, Lava) have a cost. A path through the road can be preferred even if longer. Agents can be limited to certain areas with Area Mask.
  • NavMesh Link (formerly off-mesh link) connects two disconnected surfaces, for jumping across a gap or climbing a ladder; the agent plays a custom traversal.
  • Runtime baking: NavMeshSurface.BuildNavMesh() rebuilds after procedural level generation.

How pathfinding works: A*

The NavMesh search is a graph search over polygons. The textbook version on a grid is A*: it keeps a priority queue of cells ordered by f = g + h, where g is the cost so far and h is a heuristic estimate of the remaining cost (straight-line or Manhattan distance). It always expands the most promising cell, so it finds the shortest path while exploring far fewer cells than a blind search.

C# Stand-in: A* on a grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The * marks the route the agent would walk. On a NavMesh the nodes are polygons rather than square cells, and a final "funnel" pass straightens the polygon route into corners the agent steers around.

A simple enemy brain

Pathfinding answers how to move; a state machine decides what to do. A classic guard has Patrol, Chase and Attack states with distance thresholds, plus a little hysteresis so it does not flicker between states at the boundary.

C# Stand-in: patrol, chase, attack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the player at 11 m and 16 m: the enemy is still chasing at 11 m (outside SightRange) and only gives up beyond 15 m. In Unity the Chase state calls agent.SetDestination(player.position) every few frames (not every frame; path requests are costly), Patrol cycles waypoints, and Attack stops the agent and triggers an animation. For richer behaviors, look at behavior trees (the Unity Behavior package) or utility AI.

Common mistakes

  • Calling SetDestination every frame for many agents (use a timer of 0.2 to 0.5 s).
  • Not baking again after moving level geometry.
  • Destination outside the NavMesh: use NavMesh.SamplePosition to snap to the nearest valid point.
  • Agent and Rigidbody fighting each other; make the Rigidbody kinematic or drive movement with the agent only.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does baking a NavMesh produce?

    The bake analyses geometry and builds a polygon mesh of where agents can walk.
  2. 2. In A*, what is f = g + h?

    g is the known cost from the start, h the heuristic estimate to the goal.
  3. 3. Why is the Lose range larger than the Sight range in the enemy example?

    Different thresholds for entering and leaving a state prevent rapid toggling at the boundary.
  4. 4. What does ticking Carve on a NavMesh Obstacle do?

    Carving updates the NavMesh at runtime so agents plan around the obstacle.

Summary

  • A NavMesh Surface bakes walkable areas; a NavMeshAgent follows paths with SetDestination.
  • Obstacles (carve), area costs and links shape routes; check arrival with pending, distance and velocity.
  • A* uses cost-so-far plus a heuristic to find short paths quickly.
  • A state machine with hysteresis turns movement into believable enemy behavior.

Next: Profiler and Optimization