Overview
If enemies and NPCs (non-player characters) in your game just charge straight toward players, gameplay becomes monotonous and boring. The ability to intelligently avoid walls and obstacles while finding optimal routes to destinations is essential for creating believable AI characters. NavMesh (Navigation Mesh) is Unity's standard feature for implementing this pathfinding.
The NavMesh system consists of three main elements:
- NavMesh: A polygonal mesh showing areas where AI characters can move. Automatically generated (baked) from scene geometry.
- NavMesh Agent: A component that gives the ability to move on NavMesh. Added to AI character GameObjects.
- NavMesh Obstacle: A component indicating dynamic obstacles (like opening doors). NavMesh Agents avoid these and recalculate routes.
This article covers baking NavMesh for static terrain and using NavMesh Agent to move AI characters to destinations.
Step 1: Navigation Window and NavMesh Baking
First, generate the NavMesh defining where AI can walk.
-
Open Navigation Window: Select
Window > AI > Navigationfrom the menu. This window has two main tabs:ObjectandBake. -
Configure Static Objects: NavMesh is generated based on static, non-moving objects. Select all objects that should be NavMesh generation targets—ground, walls, buildings, static obstacles—and check
Navigation Staticfrom the Inspector'sStaticdropdown in the upper right. -
Adjust Agent Settings (
Baketab): TheBaketab offers detailed NavMesh generation settings. Most important areAgent RadiusandAgent Height:Agent Radius: NavMesh Agent radius. Determines passable corridor width. Gaps narrower than this radius are treated as impassable.Agent Height: NavMesh Agent height. Determines passable ceiling clearance. Areas with ceilings lower than this become impassable.Max Slope: Maximum slope angle agents can climb.Step Height: Maximum step height agents can climb.
Adjust these values to match your AI character's actual size.
-
Bake NavMesh: When settings are complete, click
Bake. A NavMesh covered in blue polygons appears in Scene view. This is the area AI characters can traverse.
Step 2: NavMesh Agent Configuration
Next, give AI characters the ability to move on NavMesh.
-
Add NavMesh Agent Component: Select the AI character GameObject and add
Navigation > NavMesh AgentfromAdd Component. -
Adjust Agent Properties: Configure NavMesh Agent behavior in the Inspector:
Speed: Agent's maximum movement speed.Angular Speed: Rotation speed.Acceleration: Acceleration rate.Stopping Distance: How close to the destination before stopping. Setting0may cause fine vibrations as it tries to reach the exact destination—commonly set to a slightly larger value (e.g.,0.5).Radius/Height: This agent's size. Doesn't need to match Bake settings but affects collision avoidance with other agents.
Step 3: Controlling the Agent from Script
Moving a NavMesh Agent to a destination is very simple—just call the SetDestination() method from a script.
The following script is a simple enemy AI example that chases a player (object with Player tag):
using UnityEngine;
using UnityEngine.AI; // Required for NavMesh classes
[RequireComponent(typeof(NavMeshAgent))]
public class EnemyAIController : MonoBehaviour
{
private NavMeshAgent agent;
private Transform playerTarget;
void Start()
{
// Get NavMeshAgent component
agent = GetComponent<NavMeshAgent>();
// Find player object and set as target
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player != null)
{
playerTarget = player.transform;
}
}
void Update()
{
// If target (player) exists, continuously set their position as destination
if (playerTarget != null)
{
agent.SetDestination(playerTarget.position);
}
// Optional: Pass speed to Animator for walk animation
// Animator animator = GetComponent<Animator>();
// if (animator != null)
// {
// animator.SetFloat("Speed", agent.velocity.magnitude);
// }
}
}
Just attach this script to an enemy character with NavMesh Agent, and the character will automatically chase the player while avoiding obstacles in the scene.
Summary
Unity's NavMesh system enables smart AI navigation without implementing complex pathfinding algorithms yourself.
- Set static objects you want AI to traverse to
Navigation Static. - In the
Navigationwindow'sBaketab, adjust settings for character size and bake the NavMesh. - Add
NavMesh Agentcomponent to AI characters and configure speed, acceleration, etc. - In scripts, declare
using UnityEngine.AI;and callagent.SetDestination(targetPosition);to move characters.
NavMesh is an extremely powerful system applicable to many scenarios beyond enemy AI—ally NPC following, townspeople patrolling, and any character movement situations.