Part of the benefit of using Unity is the robust built-in tools that come with the editor. One of these wonderful tools is the Unity Navmesh system, allowing you to quickly prototype and even implement production-ready AI movement into your games. In this article we’ll briefly set up a simple Navmesh AI system allowing the player to traverse a space intelligently. We’ll use the previous article on Point Click movement to help facilitate where the player will go. You can visit that article here if you want to learn more.

So in an existing or fresh project, you’ll want to have a plane and a few obstacles to traverse around. You’ll also want a player object (a capsule in this case) to actually move around. Tweak your camera to give you a nice overview of the area. It should look a little something like this.

Next mark the terrain and the plane as static. Navmeshes can only be placed on static terrain.

Now we can bake the Navmesh map on to the plane. This will create the walkable area for our player. You’ll want to click Window > AI > Navigation in the editor. This will bring up the Navigation window which will let you determine what is and isn’t walkable. With the plane selected, click Object tab and ensure that the Navigation Area is marked as Walkable. Then click on the Bake tab and click Bake. We’ll leave the default settings as is. You should see a blue map show up on the plane in the Scene tab. That’s your navigation map.

Next click on the terrain objects you laid out. Head back to the Object tab and set the Navigation Area to Not Walkable, this will exclude the blocks from the navmesh that you baked. Hit the Bake tab and hit Bake button once again. Now the player will walk around the cubes and treat them like obstacles.

Here is a animated walkthrough of everything above so you have a clearer picture of what to do.

Now add a Navmesh Agent to the Player object. This allows the object to interface directly with the Navmesh. Then we’ll add the ClickMoveAgent script to the player to drive their locomotion using the NavMesh.

Here is the code for the modified ClickMove script from the previous article. In a few places we utilize the navmesh system to drive movement taking advantage of it’s ability to read the navigation map and locomotion around it and to a stop. If your player isn’t moving when you click make sure to set the player speed in the script otherwise they won’t go anywhere! Let’s see it in action.

As you can see when the player gets a target destination from the click, they move along the navmesh which then determines the best possible route to take. The agent also controls the speed, stopping distance, and slowing distance avoiding obstacles along the way. This can be a very easy and powerful way to create realistic movement for both players and AI especially when coupled with an animation system. Until next time, happy coding.