Working with Unity’s NavMesh System
Ready to make your AI move on demand?
Unity has a great tool for AI pathfinding that will allow you to easily create automatic movement for your game. My game Noise Hunters benefited from it, and I couldn’t have made it without this.
Do you want to know how to use NavMesh in your games? Then keep reading!
How to begin
First, create a new scene or use an existing one to test the NavMesh. As the name says, this pathfinding technique calculates the walkable areas represented as a “mesh” in your scene.
To bake your first walkable area, open the Navigation window at
Window > AI > Navigation and click on the Bake Tab. In this tab, you’ll be able to specify how the NavMesh should be calculated, taking into account some details such as the size or the height.
Before you click on the Bake button, you need to specify first which GameObjects in your scene are Navigation Static. Unity needs to know this to avoid creating a Walkable area for a GameObject that will likely move or be moved.
Now that you’ve done that, click on Bake, and you’ll see a blue overlay above your Static GameObject. That means that you have successfully baked a NavMesh and that your AI will be able to traverse that area!
The next step is to add the Nav Mesh Agent component to your AI or GameObject that you want to move through pathfinding. Obviously, your agent won’t move on its own. You’ll need to give it a destination.
Create a new script, and include the library UnityEngine.AI. This will allow you to reference the NavMesh components, specifically the new Nav Mesh Agent in your script. And in the Update method, add the following lines set a destination and move your AI:
Fill in those references and you’re good to go!
You’ll also have to apply the Navigation Static checkmark to every GameObject in your scene. After setting all the static GameObjects as such, my scene looks like this!
And that’s pretty much the basics! There’s a lot more to this tool that I haven’t showed you like Off Mesh Links, Obstacles, Mesh Areas, and Agent Customization. Nothing that a little experimenting, the Unity’s API, and other resources won’t cover (perhaps I can write a future article about those?).
Anyways, experiment and find what’s best for your project / game. For mine, I wanted the player to move through those narrow spaces without hugging the walls, so I raised the agent’s radius in the Navigation window, and the movement is more appropiate for this scene.