Unity: AI Navigation & Behavior
Unity ships the two halves of a typical enemy as packages: AI Navigation (com.unity.ai.navigation) bakes the navmesh and moves agents along it, and Behavior (com.unity.behavior) gives you a visual behavior graph with a blackboard. This lesson maps what you built by hand in Navigation Meshes, Behavior Trees and The Blackboard onto those packages in Unity 6. Engine code can't run on this site, so each piece comes with a small runnable model.
Baking a navmesh
Install AI Navigation from the Package Manager. Then:
- Select the level's root object and choose Add Component > Navigation > NavMesh Surface.
- Pick the Agent Type (radius, height, step height and max slope live in the Navigation window's Agents tab).
- Choose Collect Objects (all objects, a volume, or this hierarchy) and Use Geometry: render meshes, or physics colliders, which usually match what characters actually collide with.
- Press Bake. The surface stores the navmesh as an asset.
| Component | Role |
|---|---|
NavMeshSurface |
Bakes a navmesh for one agent type; BuildNavMesh() rebakes from script |
NavMeshModifier / NavMeshModifierVolume |
Exclude objects or change the area type (water, road) |
NavMeshAgent |
Plans a path and steers along it, with local avoidance |
NavMeshObstacle |
A moving obstacle; with Carve on it cuts a hole in the navmesh |
NavMeshLink |
Connects two places the bake left apart: a jump, a ladder, a door |
Tip: Carving rebuilds part of the navmesh, so turn it on only for obstacles that stop and stay (a crate pushed into a doorway), with Carve Only Stationary enabled. For things that keep moving, let agents avoid them instead.
Moving an agent
NavMeshAgent does the path request and the corner following for you. The calls you'll use most:
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class PatrolAgent : MonoBehaviour
{
[SerializeField] Transform[] waypoints;
NavMeshAgent agent;
int index;
void Awake()
{
agent = GetComponent<NavMeshAgent>();
agent.stoppingDistance = 0.5f;
agent.autoBraking = false; // keep speed between patrol points
}
void Start() => agent.SetDestination(waypoints[index].position);
void Update()
{
// pathPending: the path is still being computed, so remainingDistance isn't valid yet.
if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance)
{
index = (index + 1) % waypoints.Length;
agent.SetDestination(waypoints[index].position);
}
}
}The pathPending check is the line people forget. SetDestination doesn't always produce a path in the same frame, and until it does, remainingDistance doesn't describe the new path. Without the check, an agent can "arrive" instantly and skip waypoints. This model makes each path request take two frames, and remainingDistance reads 0 while it is pending:
using System;
foreach (bool checkPending in new[] { false, true })
{
Console.WriteLine(checkPending ? "with pathPending check:" : "without pathPending check:");
var agent = new Agent();
double[] waypoints = { 4, 8, 2 };
int index = 0;
agent.SetDestination(waypoints[index]);
for (int frame = 0; frame < 10; frame++)
{
agent.Tick();
string state = agent.PathPending ? "pending" : quot;x={agent.X:F1}";
string line = quot; frame {frame}: {state,-7} remaining={agent.RemainingDistance:F1}";
bool ready = !checkPending || !agent.PathPending;
if (ready && agent.RemainingDistance <= agent.StoppingDistance)
{
index = (index + 1) % waypoints.Length;
agent.SetDestination(waypoints[index]);
line += quot; -> next waypoint {waypoints[index]}";
}
Console.WriteLine(line);
}
}
class Agent
{
public double X, Speed = 2, StoppingDistance = 0.5, RemainingDistance;
public bool PathPending;
double destination;
int framesUntilPath;
public void SetDestination(double d)
{
destination = d;
PathPending = true;
framesUntilPath = 2; // the path query finishes two frames later
RemainingDistance = 0;
}
public void Tick()
{
if (PathPending)
{
if (--framesUntilPath > 0) return;
PathPending = false;
}
X += Math.Clamp(destination - X, -Speed, Speed);
RemainingDistance = Math.Abs(destination - X);
}
}without pathPending check:
frame 0: pending remaining=0.0 -> next waypoint 8
frame 1: pending remaining=0.0 -> next waypoint 2
frame 2: pending remaining=0.0 -> next waypoint 4
frame 3: pending remaining=0.0 -> next waypoint 8
frame 4: pending remaining=0.0 -> next waypoint 2
frame 5: pending remaining=0.0 -> next waypoint 4
frame 6: pending remaining=0.0 -> next waypoint 8
frame 7: pending remaining=0.0 -> next waypoint 2
frame 8: pending remaining=0.0 -> next waypoint 4
frame 9: pending remaining=0.0 -> next waypoint 8
with pathPending check:
frame 0: pending remaining=0.0
frame 1: x=2.0 remaining=2.0
frame 2: x=4.0 remaining=0.0 -> next waypoint 8
frame 3: pending remaining=0.0
frame 4: x=6.0 remaining=2.0
frame 5: x=8.0 remaining=0.0 -> next waypoint 2
frame 6: pending remaining=0.0
frame 7: x=6.0 remaining=4.0
frame 8: x=4.0 remaining=2.0
frame 9: x=2.0 remaining=0.0 -> next waypoint 4
Without the check, every pending frame looks like "arrived", so the agent cycles through all three waypoints without moving and never gets anywhere. With the check, it waits for each path, walks it, and only then asks for the next point. Keep the check; it costs nothing.
Behavior graphs
The Behavior package adds a graph editor (Unity calls the asset a behavior graph: a behavior tree that can also branch and merge). Create one with Create > Behavior > Behavior Graph, then add the Behavior Agent component (BehaviorGraphAgent) to the character and drag the graph into its Behavior Graph field. The graph's blackboard holds variables such as Target, PatrolPoints or Alerted, and code can set them per agent:
using Unity.Behavior;
using UnityEngine;
public class GuardSenses : MonoBehaviour
{
[SerializeField] BehaviorGraphAgent behavior;
public void OnPlayerSpotted(GameObject player)
{
behavior.SetVariableValue("Target", player);
behavior.SetVariableValue("Alerted", true);
}
}To write your own node, right-click in the graph and choose Create new > Action. You describe it as a sentence ("[Agent] waits at [Point]"), and Unity generates a script whose fields are blackboard variables. You then fill in the three overrides. OnStart and OnUpdate return a Status: Running keeps the node active, Success or Failure finishes it.
using System;
using Unity.Behavior;
using Unity.Properties;
using UnityEngine;
using Action = Unity.Behavior.Action;
[Serializable, GeneratePropertyBag]
[NodeDescription(name: "Look Around", story: "[Agent] looks around for [Seconds] seconds", category: "Action")]
public partial class LookAroundAction : Action
{
[SerializeReference] public BlackboardVariable<GameObject> Agent;
[SerializeReference] public BlackboardVariable<float> Seconds;
float endTime;
protected override Status OnStart()
{
endTime = Time.time + Seconds.Value;
return Status.Running;
}
protected override Status OnUpdate()
{
Agent.Value.transform.Rotate(0f, 90f * Time.deltaTime, 0f);
return Time.time >= endTime ? Status.Success : Status.Running;
}
protected override void OnEnd() { } // also runs when a higher-priority branch interrupts us
}The generated file also contains an id in the attribute; keep what Unity wrote. This is exactly the running-status protocol from Decorators, Running & Aborts: a node that returns Running gets OnUpdate again next tick, and OnEnd is where you clean up, whether the node finished or was interrupted.
Debugging
- In the Scene view, the AI Navigation overlay toggles navmesh and agent path display.
- In the behavior graph editor, the Debug toolbar menu picks an agent; in Play mode every node shows its status icon.
- For anything the tools don't show (scores, perception rays), draw it yourself with
GizmosandDebug.DrawLine(see Debugging AI).
For the rest of the engine, see Unity with C#.
Test yourself
Why check agent.pathPending before reading remainingDistance?
- remainingDistance is in a different unit while pending
- Until the new path is ready, remainingDistance doesn't describe it, so the agent can look like it has already arrived
- pathPending stops the agent from moving
- It is required to bake the navmesh
A crate sometimes gets pushed into a corridor and stays there. What is the usual setup?
- Rebake the whole NavMeshSurface every frame
- A NavMeshObstacle with Carve and Carve Only Stationary enabled
- A NavMeshLink across the crate
- Make the crate a NavMeshAgent
In a custom Unity Behavior Action, what does returning Status.Running from OnUpdate mean?
- The node failed
- The node is still working and will be updated again next tick
- The graph restarts
- The agent starts running animation