Modular Waypoint System in Unity

Creating an AI patrol path may look intimidating at first glance so let’s dive in and demistify the process.

First things first, we need to add the navmesh agent to our AI and bake the navmesh. Don’t forget to mark any obstacles as “static”.

The next thing we need to do is to setup the waypoints that we want the AI to travel between. The easiest way to visualize this is to place a physical object in the scene in the locations desired, then remove the mesh component (and any other components you don’t want:

I’ve kept the collider component for the sake of visualization

To keep things organized, you should name your locations. Something like “PointA”, “PointB”, “PointC”, etc will suffice.

Now it’s time to make our character move using script. Let’s setup some variables first. We’ll need a list of our positions, a reference to our agent component, an integer to keep track of which location we are at and a bool to determine whether we are headed to the start or the end:

Also, we can’t forget to add the AI library at the top of the file:

The only code we will be using in Start() is to set our reference to the NavMesh Agent:

At this point we can set the destination to the first location in our wayPoint list…we also need to confirm that there is a target to begin with:

This will get us to the first position (if there is one) but that is it. From here we need to know if we are at our target in order to move to the next. We can do that with Vector3.Distance(). Let’s create a simple method that returns this:

We can use that distance and check if we are in range with a value of 1.5f. Now we just need to increment our waypoint until we reach the end of our list, then decrement until we hit the first point:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store