Working with Unity’s NavMesh System for Smart AI

Objective: Creating an area for the guards to patrol

Jean-Noel Seneque
3 min readAug 24, 2021

In this article, I want to share how I was able to make the guards patrol a certain section.

First, we add the Nav Mesh Agent component to each of the security guards so they can utilise the NavMesh Surface baked earlier.

Adding the Nav Mesh Agent component

Now the guards know where they can walk, it is time to set the points where they need to walk to. Create a Guard AI script.

In the script add a List to store each of the points the guard will patrol towards.

Add the GuardAI script to each of the Guards and now create empty game objects to represent the points. Drag each of them in order to the List for each of the guards.

In this screenshot, you can see each of the waypoints and I have drawn the guard's path.

In this example, the Yellow diamond icons were used to easily identify each of the waypoints.

Next, we drag on each of the waypoints in the correct order to the Guard AI script.

With the waypoints assigned for the first guard, let’s add the code to move the guard from waypoint to waypoint and then in reverse.

Now, for this demonstration, I have brought the two waypoints closer so we can see the guard moving between the two waypoints. Let’s give our guard a rest at each point. We check if the waypoint is at the beginning or end and only pause the guard at those points.

Update method
PauseGuard Coroutine

That’s it. We now have the guard pausing at the start and end waypoints and moving through any waypoints in between.

If you enjoyed reading this article give me a Clap, also if you would like to see more, “Follow” me, so you may be notified of future releases. You may also send me a message if you need any further help.

--

--

Jean-Noel Seneque

A Data & Analytics Consultant who is expanding into developing experiences in XR, Enterprise and Gaming space using Unity www.jeannoelseneque.com