NavMesh & AI Navigation
Enemies that walk around walls, find doors and climb stairs need pathfinding. Unity's AI Navigation package (com.unity.ai.navigation) builds a NavMesh, a simplified polygon map of the walkable surfaces, and a NavMeshAgent component finds and follows paths on it while steering around other agents.
Migrating: In Unity 6 the NavMesh is baked with the NavMesh Surface component from the AI Navigation package. The old Navigation window bake (Object/Bake tabs) is legacy; the package can convert old scenes.
Setting it up
- Install AI Navigation from the Package Manager.
- Create an empty GameObject
NavMeshand add NavMesh Surface. Choose which objects to collect (all, a volume, or children) and which layers count. - Click Bake. The walkable area appears as a blue overlay in the Scene view.
- Define agent types (radius, height, max slope, step height) in the Navigation settings; small and large monsters need separate surfaces.
- Doors and moving crates get a NavMesh Obstacle with Carve ticked, so agents path around them. Jumps and drops between areas are NavMesh Link components.
Moving an agent
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class Chaser : MonoBehaviour
{
[SerializeField] Transform target;
[SerializeField] float repathInterval = 0.25f;
NavMeshAgent agent;
float nextRepath;
void Awake() => agent = GetComponent<NavMeshAgent>();
void Update()
{
if (target == null) return;
if (Time.time >= nextRepath) // don't repath every frame
{
nextRepath = Time.time + repathInterval;
agent.SetDestination(target.position);
}
bool arrived = !agent.pathPending && agent.remainingDistance <= agent.stoppingDistance;
if (arrived) Attack();
}
void Attack() { /* ... */ }
public static bool TryRandomPointNear(Vector3 center, float radius, out Vector3 point)
{
Vector3 candidate = center + Random.insideUnitSphere * radius;
if (NavMesh.SamplePosition(candidate, out NavMeshHit hit, 2f, NavMesh.AllAreas))
{
point = hit.position; // snap to the closest point on the NavMesh
return true;
}
point = center;
return false;
}
}Useful members: agent.speed, angularSpeed, acceleration, stoppingDistance, isStopped, velocity, hasPath, path.corners (for drawing the path), agent.Warp(p) (teleport onto the mesh) and NavMesh.CalculatePath (ask without moving).
Note: A NavMeshAgent moves the transform itself. Don't put a non-kinematic Rigidbody on the same object, or the two fight. For animated characters, set
agent.updatePosition = falseand drive the Animator fromagent.desiredVelocityif you want root motion.
What the pathfinder does: a model
The real NavMesh runs A* over polygons and then smooths the path (the "string-pulling" funnel algorithm). The model runs A* over a small grid, which shows the same behaviour: the shortest route around walls, and a choice of area costs (NavMesh areas such as "Mud" can cost more, so agents avoid them when a detour is cheap):
using System;
using System.Collections.Generic;
string[] map =
{
"..........",
".########.",
"S~~~~~~~~G",
".########.",
"..........",
};
foreach (int mudCost in new[] { 1, 5 })
{
var (path, cost) = AStar(map, mudCost);
Console.WriteLine(quot;mud cost {mudCost}: {path.Count - 1} steps, total cost {cost}");
var grid = Array.ConvertAll(map, r => r.ToCharArray());
foreach (var (x, y) in path) if (grid[y][x] is '.' or '~') grid[y][x] = '*';
foreach (var row in grid) Console.WriteLine(" " + new string(row));
}
static (List<(int, int)>, int) AStar(string[] map, int mudCost)
{
(int, int) start = default, goal = default;
for (int y = 0; y < map.Length; y++)
for (int x = 0; x < map[y].Length; x++)
{
if (map[y][x] == 'S') start = (x, y);
if (map[y][x] == 'G') goal = (x, y);
}
var open = new PriorityQueue<(int, int), (int, int)>(); // priority: (f, insertion order)
var cameFrom = new Dictionary<(int, int), (int, int)>();
var g = new Dictionary<(int, int), int> { [start] = 0 };
int order = 0;
open.Enqueue(start, (H(start, goal), order++));
var dirs = new[] { (1, 0), (0, 1), (-1, 0), (0, -1) };
while (open.Count > 0)
{
var cur = open.Dequeue();
if (cur == goal) break;
foreach (var (dx, dy) in dirs)
{
var (nx, ny) = (cur.Item1 + dx, cur.Item2 + dy);
if (ny < 0 || ny >= map.Length || nx < 0 || nx >= map[ny].Length || map[ny][nx] == '#') continue;
int step = map[ny][nx] == '~' ? mudCost : 1;
int ng = g[cur] + step;
if (g.TryGetValue((nx, ny), out int old) && old <= ng) continue;
g[(nx, ny)] = ng;
cameFrom[(nx, ny)] = cur;
open.Enqueue((nx, ny), (ng + H((nx, ny), goal), order++));
}
}
var path = new List<(int, int)> { goal };
while (path[^1] != start) path.Add(cameFrom[path[^1]]);
path.Reverse();
return (path, g[goal]);
}
static int H((int x, int y) a, (int x, int y) b) => Math.Abs(a.x - b.x) + Math.Abs(a.y - b.y); // Manhattanmud cost 1: 9 steps, total cost 9
..........
.########.
S********G
.########.
..........
mud cost 5: 13 steps, total cost 13
..........
.########.
S~~~~~~~~G
*########*
**********
With normal ground costs the agent wades straight through the mud (~); when mud costs 5 per cell, the 9-step route through it costs 41, so the 13-step detour (cost 13) wins and the agent walks around. NavMesh areas work the same way: set their costs under the Navigation settings' Areas tab and per agent with agent.SetAreaCost.
The deeper theory (A*, heuristics, flow fields, steering) is in the Game AI course.
Performance
- Hundreds of agents calling
SetDestinationevery frame is a common performance hole. Repath on a timer, or only when the target moved more than a metre. - Carving obstacles re-cuts the NavMesh; only carve when the obstacle stops moving (Carve Only Stationary).
- For runtime-generated levels, call
navMeshSurface.BuildNavMesh()after generating, orUpdateNavMeshasynchronously for changes.
Test yourself
Which component bakes the NavMesh in Unity 6 with the AI Navigation package?
- NavMeshAgent
- NavMesh Surface
- NavMesh Obstacle
- Terrain
How do you check that an agent has reached its destination?
agent.isStopped!agent.pathPending && agent.remainingDistance <= agent.stoppingDistanceagent.velocity == Vector3.zeroonlyagent.hasPath == falseonly
A door that opens and closes should block agents while closed. What do you add?
- A NavMesh Link
- A NavMesh Obstacle with Carve enabled
- A second NavMesh Surface
- A Rigidbody