Failed to create agent because it is not close enough to the NavMesh
Failed to create agent because it is not close enough to the NavMesh
A NavMeshAgent was enabled, and Unity could not find a NavMesh near enough to place it on. The agent stays off the mesh, so path calls on it fail afterwards with the SetDestination error.
Read the Console line first
Note where the object is when it spawns. In the Scene view, the blue NavMesh overlay has to be under that point.
Common causes
There is no baked NavMesh, or it was baked for another agent type
Bake a NavMeshSurface for the agent type the NavMeshAgent uses.
The spawn point is off the mesh
The agent is instantiated in the air, inside a wall, or at a point the bake left out, such as a spot narrower than the agent radius.
The NavMesh is baked at runtime and not ready
Procedural levels that bake a NavMeshSurface after spawning agents enable them before the mesh exists.
The fix
// Keep the agent disabled on the prefab, place it, then enable it
var enemy = Instantiate(enemyPrefab);
if (NavMesh.SamplePosition(spawnPoint, out var hit, 3f, NavMesh.AllAreas))
{
enemy.transform.position = hit.position;
enemy.GetComponent<NavMeshAgent>().enabled = true;
}Stop it coming back
Bake before spawning, snap spawn points with NavMesh.SamplePosition, and enable agents only once they are on the mesh.
Questions
- Why does spawning at the right position still fail?
- If you Instantiate the prefab at the origin and move it afterwards, the agent is created at the origin, which may be off the mesh. Pass the position to Instantiate,
Instantiate(prefab, spawnPoint.position, spawnPoint.rotation), so the agent starts where it belongs. - How do I snap a spawn point onto the NavMesh?
- Call
NavMesh.SamplePosition(point, out NavMeshHit hit, 2f, NavMesh.AllAreas)and spawn athit.positionwhen it returns true. - I bake the NavMesh at runtime. How do I avoid this?
- Call
surface.BuildNavMesh()on your NavMeshSurface before spawning agents, or keep agents disabled until the bake finishes and then enable them.
Scripts that avoid it
- NavMesh Click-to-MoveClick-to-move character controller using NavMeshAgent. Click anywhere to navigate, with destination marker and path line.
- Waypoint Patrol AI ProAdvanced patrol AI with NavMesh pathfinding, player detection with awareness meter, alert states, group coordination, and patrol schedules.
Related errors
Got a different error? Paste it into the error lookup.