Navmesh Surface
Updated
The scene’s walkable navmesh that agents find paths on.
- Type
ent-navmesh-surface- Script class
NavMeshSurfaceEntity- Family
- Navigation
Overview
Section titled “Overview”A NavMesh Surface owns the scene’s navmesh (navigation mesh): a simplified map of every place a character can stand, which characters use to find their own way around walls and through doors. The map is baked, that is computed once, from the surfaces you mark as walkable and the obstacles you mark as collidable. The surface keeps the result, so play loads it at once. It also runs the crowd: every character with a NavMesh Agent moves in it and avoids the others.
Put one NavMesh Surface in a scene that has characters who walk on their own. It has no position of its own, because the navmesh covers the geometry wherever it is. Only one surface is used across the active scenes.
- In the editor, selecting the surface draws the navmesh over the scene, and the Bake action computes it.
- In play, agents join the navmesh a few frames after play starts. Without baked data, play bakes the navmesh when it is first needed, which delays the characters.
The other navigation pieces are components and one sibling entity: NavMesh Walkable marks floors, NavMesh Collidable marks obstacles, a NavMesh Agent moves a character, and a NavMesh Link joins areas the surface does not otherwise connect, such as a gap to jump.
The bake settings that matter most:
agentRadiusis the clearance kept from walls and edges, in metres. It is independent of the radius each NavMesh Agent has in play.agentHeightis the headroom a character needs, in metres. Places under a lower ceiling are left out.agentMaxClimbis the tallest step a character climbs, andagentMaxSlopethe steepest walkable slope, in degrees.cellSizeandcellHeightset the resolution. Smaller cells follow edges more closely but take longer to bake.
The other settings tune how the outline is simplified; the table below lists them with their ranges.
Set it up
Section titled “Set it up”- Add a NavMesh Surface entity to the scene. See Scenes and hierarchy.
- Add a NavMesh Walkable component to floors, ramps and platforms, and a NavMesh Collidable to walls, furniture and crates.
- Set
agentRadius,agentHeight,agentMaxClimbandagentMaxSlopeto match your characters. - Select the surface to see the navmesh, and bake it. Bake again whenever you move walls, floors or links.
- Give each character a NavMesh Agent, usually with a Character Controller on the same entity.
Examples
Section titled “Examples”Tell other scripts when paths are ready
Section titled “Tell other scripts when paths are ready”Wait until the navmesh and crowd are live, then announce it once.
#pragma lifecycle(startup, update)
let surface;let announced = false;
function startup() { surface = findEntity('NavMesh Surface')?.getComponent(NavMeshSurfaceComponent);}
function update() { if (announced || !surface || !surface.isReady) return; announced = true; emit('nav/ready'); log('Navigation is ready');}How it works:
getComponent(NavMeshSurfaceComponent)reaches the surface’s component, which holds the navmesh and the queries.isReadybecomestrueonce the navmesh and its crowd are live, a few frames into play.- Scripts that move characters can start on
on('nav/ready', …)instead of retrying every frame.
Scatter pickups where players can reach them
Section titled “Scatter pickups where players can reach them”Place coins at random spots that are guaranteed to be on walkable ground.
#pragma lifecycle(startup)
const COUNT = 10;const AREA = 15; // metres around the centre
function startup() { const surface = findEntity('NavMesh Surface').getComponent(NavMeshSurfaceComponent); const centre = { x: 0, y: 0, z: 0 };
on('nav/ready', () => { for (let i = 0; i < COUNT; i++) { const spot = surface.randomPointAround(centre, AREA); if (!spot) continue; spawn('Coin', { position: { x: spot.x, y: spot.y + 0.5, z: spot.z }, enabled: true }); } });}How it works:
- The script waits for
nav/ready, sent by the previous example, so the navmesh exists before it is queried. randomPointAround(center, radius)returns a random reachable point withinradiusofcenter, orundefinedwhen there is none.spawncopies a disabledCointemplate to each point, half a metre above the ground.
Check that a goal can be reached
Section titled “Check that a goal can be reached”Before sending a character somewhere, check that a path exists and measure how long it is.
#pragma lifecycle(startup)
function pathLength(corners) { let length = 0; for (let i = 1; i < corners.length; i++) { const a = corners[i - 1]; const b = corners[i]; length += Math.hypot(b.x - a.x, b.y - a.y, b.z - a.z); } return length;}
function startup() { const surface = findEntity('NavMesh Surface').getComponent(NavMeshSurfaceComponent); const from = new THREE.Vector3(); const to = new THREE.Vector3();
on('route/check', (data) => { findEntity(data.from)?.getWorldPosition(from); findEntity(data.to)?.getWorldPosition(to); const start = surface.closestPoint(from); const goal = surface.closestPoint(to); const corners = start && goal ? surface.computePath(start, goal) : []; if (corners.length === 0) log('No route from', data.from, 'to', data.to); else log('Route of', pathLength(corners).toFixed(1), 'm with', corners.length, 'corners'); });}How it works:
closestPointsnaps each position onto the navmesh, or returnsundefinedwhen nothing is near.computePath(from, to)returns the corners of the path between two points; an empty list means the goal cannot be reached.- The length is the sum of the distances between corners. Emit
route/checkwith{ from: 'Guard', to: 'Treasure' }to try it.
Rebuild the navmesh after the level changes
Section titled “Rebuild the navmesh after the level changes”Bake again at runtime when a script has built or changed the level.
#pragma lifecycle(startup)
function startup() { const surface = findEntity('NavMesh Surface').getComponent(NavMeshSurfaceComponent);
// Another script builds a maze, then emits 'maze/built'. on('maze/built', async () => { emit('hud/toast', { text: 'Preparing paths…' }); const ok = await surface.bake((progress) => log(`Baking ${Math.round(progress * 100)}%`)); emit(ok ? 'maze/ready' : 'maze/failed'); });}How it works:
bake(onProgress)computes a fresh navmesh from the current geometry and links, replaces the live one, and callsonProgresswith how much is done, from 0 to 1.- It returns a promise of
trueon success, so theasynclistener canawaitit. It resolvesfalsewhen there was nothing to bake, the surface is off, or the bake was stopped. - The bake works a little each frame, so the game keeps running while it does.
cancel()stops a bake under way.
- Bake in the editor before you publish. A scene without baked data bakes on load, and characters wait until it is done.
- If characters walk through a wall, give the wall a NavMesh Collidable and bake again. If they refuse a floor, check that it has a NavMesh Walkable and is not steeper than
agentMaxSlope. - If nothing is marked walkable or collidable, the bake uses every visible mesh, so a first bake still gives something. Mark your geometry for a clean result.
Components
Section titled “Components”What a new Navmesh Surface is made of. Required components are always present and cannot be removed; the others can. Per entity says whether an entity can hold one of that component or several. Layer, Lock and Enable are on every placed entity, and Transform holds its position, rotation and scale.
| Component | Type | Role | Per entity | What it does |
|---|---|---|---|---|
| Layer | comp-layer |
Required | One | Puts the entity on a render/raycast layer so cameras and rays can include or skip it. |
| Lock | comp-lock |
Required | One | Editor-only flag that stops the entity from being selected or moved. |
| Enable | comp-enable |
Required | One | Turns the entity and its children on or off: hides them and stops their behavior. |
| Navmesh Surface | comp- |
Required | One | The scene’s walkable navmesh that agents find paths on. |
You can also add 1 optional components, such as Signal Emitter.
The settings of a new entity, as the runtime creates it. Change them in the Properties panel of XR Creator, or from a script with getComponent(…).setProps({ … }).
| Prop | Default | Range |
|---|---|---|
cellSize |
0.166 |
0.1 ≤ x ≤ 10 |
cellHeight |
0.1 |
0.1 ≤ x ≤ 1 |
agentHeight |
1.7 |
0. |
agentRadius |
0.5 |
0 ≤ x ≤ 5 |
agentMaxClimb |
0.3 |
0 ≤ x ≤ 10 |
agentMaxSlope |
45 |
0. |
regionMinSize |
4 |
0 ≤ x ≤ 150 |
region |
20 |
0 ≤ x ≤ 150 |
edgeMaxLen |
12 |
0 ≤ x ≤ 50 |
edgeMaxError |
1 |
0 ≤ x ≤ 3 |
vertsPerPoly |
6 |
3 ≤ x ≤ 6 |
detail |
6 |
0 ≤ x ≤ 16 |
detail |
1 |
0 ≤ x ≤ 16 |
Events
Section titled “Events”With a Signal Emitter on the entity, these events reach scripts as { entityId, eventType, data }. Compare eventType with the EventType constants.
It reports the events every entity has: Transform::change (and position-change, rotation-change, scale-change), Enable::change, Layer::change and Lock::change.
Live example
Section titled “Live example”Run it in the browser, read its scripts, and download it as an XR Creator project.
A villager picks a random reachable point near home with randomPoint, walks there with its Character Controller, rests two to five seconds on arrive, and sets off again.
Watch the villager wander around the walls, resting between walks. Drag to orbit the camera, scroll to zoom.
From a script
Section titled “From a script”Find the entity by its name, check its class, and work with its components. Name the entity in the Hierarchy first; this example expects My Navmesh Surface.
#pragma lifecycle(startup)
function startup() { // Find the entity by the name it has in the Hierarchy. const entity = findEntity('My Navmesh Surface'); if (!(entity instanceof NavMeshSurfaceEntity)) return;
// Its Navmesh Surface component holds the settings listed under Props. const component = entity.getComponent(NavMeshSurfaceComponent); log('cellSize is', component.props.cellSize); component.setProps({ cellSize: 0.25 });}