Using NavMesh Obstacles in Unity
Today we visit the scene of an emergent urban tragedy: a tremor has collapsed some pedestrian walkways, leaving a bystander trapped beneath the rubble! Luckily, we have a pair of heroes on the scene, ready to save the day.
Thus the stage is set for today’s demonstration.
From a gameplay perspective, we need to be able to interact with objects on the scene that can be moved, but we also need those objects to prevent NavMesh agents from walking through them.
These two goals are in conflict. If we bake these objects into the NavMesh in the editor, then moving them during runtime will leave invisible obstructions in the NavMesh. Dropping the object in a new location will not create a new impassible area; the NavMesh Agents will ignore the obstacle completely, trusting the NavMesh to indicate where it can and cannot move.
We could re-bake the NavMesh during runtime, but the larger our levels get the more that’s going to slow down gameplay.
Enter the NavMesh Obstacle component.
This component can be added to any object in the scene. It will make the object carve a hole in the NavMesh while it is stationary, and the hole will disappear when the object moves. There are a few options to customize this behavior, including adjusting the size and shape of the obstacle area (useful for strangely shaped objects), but the default settings should fit most uses.
Let’s see how my scene looks with all my movable blocks using the NavMesh Obstacle component, rather than being baked into the mesh:
Great! Well, clearly I need to be mindful of where I let the player drop a block… but otherwise, great! You can see the mesh updates any time our blocks start or stop moving, ensuring that an obstacle at rest remains an obstacle no matter where it rests.