Feature Highlight: Using Unity’s NavMesh System for Smart AI

The Unity NavMesh System allows you to set the rules for player or AI movement in your game. You can ‘bake’ a navigation landscape in your scene allowing you to specify which areas can be pathed by your characters.

NavMesh is a great tool for keeping your characters ‘in bounds’ and provides a an easy to understand visual representation of the navigable areas of your scene. You can even modify settings for things like the step height, how big a step your player is allowed to traverse over, or buffer distance between objects in your scene to be sure your characters are not clipping through any art assets.

Fortunately NavMesh is a pretty smart (but still not perfect) tool that can calculate a pretty solid navigable area of your scene automatically. Step 1 is to select whatever the floor object of your game is (this should have a collider component) and we will use that object as the focus for baking our NavMesh.

In this stealth adventure game, we have an object called FloorCollider that we will use for this purpose. You can see a part of the mesh for this collider outlines in green above.

Step 2: Navigate to Window -> AI -> Navigation. Inside this window you will see a tap for Bake with a number of settings inside:

This nifty tool allows you to specify the height and width (via Radius) of your characters that will need to navigate the scene, as well as the maximum slope and step height your player should be able to traverse / climb. We have literal stairs in our game, so the slope and step height settings are particularly important to get right. Fortunately you can bake the NavMesh and see in real-time if the system is calculating that your stairs are traversable.

Once you click bake, the floor object of your scene will turn blue. Any area covered in blue has been deemed traversable by the player and any AI characters in your game. You will notice in the image above that there are a few gaps along the stairs. Small gaps like this will still usually be traversable as long as there is solid blue coverage along the incline plane. However, some other areas in our game do have problems.

This staircase for example has a large gap that disconnects the floor path from the stairs path, and our player will not be able to climb this gap as it stands. To fix this we can increase our allowable step height value from 0.4 to 0.5, and you can now see the two paths are connected.

As this example illustrates, when baking a NavMesh it is important to check your scene to ensure all of your intended pathing is allowed by the mesh.

Now that our NavMesh is baked, we are ready to set up player movement and AI ‘enemy’ behavior. Both will take advantage of this NavMesh when calculating their movement. Let’s get to it — see ya there!

Unity Developer from Los Angeles, CA