Creating Modular Waypoint System in Unity

Christian Carter
3 min readNov 4, 2021

This tutorial will cover how to add enemy guard AI that uses a modular waypoint system. First create a script for your guard. Add it to your guard. Also, add a Nav Mesh Agent to it as well.

In the script add a variable list for the waypoints that will hold Transforms.

public List<Transform> wayPoints;

Now, in the Unity editor you will be able to set how many waypoints each guard will have. You can duplicate your guard and use them for the waypoints. Put them in their own empty GameObject. You can remove the NavMesh Agent and the script from the guards you will be using as waypoints. You can also remove the Character and Guard-Rigged from the points as well.

Assign your waypoints to your guard under their waypoint list.

Now in the script add a variable to track the Transform of the current target, which is the current waypoint the guard is moving to. Also, add a variable to track the position in the list of the current target using an int and a bool variable to check if the guard is reversing through the waypoints. Make sure you assign the NavMeshAgent in the Start function.

private NavMeshAgent _agent;
private int _currentTarget = 0;
private bool _reverse = false;
void Start()
{
_agent = GetComponent<NavMeshAgent>();
}

Next, create a Move function. Make sure you call the move function in the Update function. This is where everything will happen. First check that there are waypoints and they are not null. Set the Destination of the NavMeshAgent. Check the distance between the current position and the distination position. If it is less than 1 check if it is reversing its direction or not and increment or decrement accordingly. Make sure when you reach the end of the waypoint list you switch reverse so that it will not go outside the list.

void Move()
{
if (wayPoints.Count > 0 && wayPoints[_currentTarget] != null)
{
_agent.SetDestination(wayPoints[_currentTarget].position);
float distance = Vector3.Distance(transform.position,
wayPoints[_currentTarget].position);
if (distance < 1f)
{
if (_reverse)
{
_currentTarget--;
if (_currentTarget == 0)
{
_reverse = false;
}
}
else
{
_currentTarget++;
if (_currentTarget == wayPoints.Count - 1)
{
_reverse = true;
}
}
}
}
}

This will allow each of your guards to move based on the waypoints you assign to them.

-Chris

--

--