Working with Unity Nav Mesh Ai

Understanding how to move a Ai Agent within a Nav Mesh surface

Simon Truong
3 min readFeb 20, 2023


Continuing from the previous article, we will now expand our experience with working with Nav Meshes. In this article we will make the Nav Mesh Agent move towards a randomly assigned waypoint.


First we are going to create an new C# script called “Ai” and attach it to the red sphere. In the Ai script were are going to gain access to the Unity Ai Library.

In order to allow the Ai to ping pong between the waypoints we first need to create an array containing all the waypoint Transform. At the same time we are also going to assign the current destination point(waypoint) along with access to the Nav Mesh Agent component.

In the start method we are going to get the Nav Mesh component and assign it to our local variable.

Next we are going to create a new method which is called “Go to Next Point”. Start with an null check by doing a return function IF the waypoint equals zero. (By Default the waypoints should equal the amount of total waypoints setup)

In Unity, the Nav Mesh Agent as several functions which can be used to move an object from destination to another. The one we are going to use is “_agent.destination” which will set the destination of the Ai Nav Mesh. We want the destination to be the waypoint array with the preset int position.

Then we are going to cycle through the destination points once the Ai object as reach the current selected waypoint. To make the destination random, we are going to create a new variable called “Next Point” and set the random range from 0 to the total length of the waypoint array.

To make all these function complete we are going to set the distance between the current Ai Nav Mesh Agent to the next waypoint, and when the distance is less than 0.5f, we will move to the next point.

Back in Unity, we are going to plug in our Array with all the waypoints.

I also adjusted the overall environment a tad bit by adding several cubes blocking waypoint 5.

After setting up the new boundaries we need to open up the Navigation tab and re-bake the area so the Nav Mesh can identify with the barriers and not collided with them.

The final result should look something like this:



Simon Truong

A Designer, an Illustrator and a massive tech geek aspiring to become a professional Unity Developer.