Creating Modular Waypoint System in Unity

Waypoint movement without animation

To create a waypoint system on a Nav Mesh is pretty easy, but what about it’s modularity? First things first: we need to get the AI agent moving. in order to allow the AI objects to recognize that they are a Mesh Agent and will move on a Nav Mesh system, we need to make sure that we have added Nav Mesh Agent component to them.

Certainly, we will have many AI elements moving differently in our games. To avoid unnecessary scripting, it’a always better to use a single script for the same type of game objects if it’s possible.

To set different waypoints to different agents, we can define a Transform List and then manipulate them from the Inspector.

To define the Transform points, we can either duplicate the game ojbect and remove it’s components or create an empty game object and position the empty game objects on the start and end points of the waypoint.

Since each Agent on the scene will use an instance of the Guard AI script, we can assign different Transform’s to each of the agents. In other words, each AI agent will have its own waypoints to be assigned from the inspector.

The only thing left is to add the behavior from the script. First, we need to give reference to Nav Mesh Agent component and access it within the script.

(Of course, do not forget to null check.)

Now we are ready to create our waypoint.

To get the AI Agent moving to a waypoint position, we need to use SetDestination method, which takes the target as a Vector3 parameter. However, making the AI Agent to patrol between 2 points is another issue. We need to find a way to tell the agent to move to the next waypoint once it reaches its previous target. Additionally, we need to make sure that we will not face any null return error as multiple AI’s with different number of waypoints will share a single script.

In order to avoid these problems, we need to create a lean and efficient line of code. I will try to demonstrate each of these steps one by one.

First of all, in order to prevent the null return, we can make sure that an AI agent instance has at least one waypoint attached: By checking if the waypoint List has a count of greater than 0 and the current target waypoint is not empty.

To properly code the target waypoints correctly, we need to define a boolean variable, which will be true if the agent is on return. By increasing the targeted waypoint index while return is false and increasing it while true.

Just as explained on my previous article, to find out if the agent reached to the target destination, we can use Vector3.Distance function. To control the waypoints index, an int variable (currentTargetIndex) has been defined.

With the code below, now all of the agents with this script will be able to move in between their waypoints.

Unity Developer