Creating Modular Waypoint System in Unity

Jaime
2 min readJul 3, 2021

--

Say we have a Sphere that we would like to use to patrol the four corners of the ground. The requirement is that once it reaches from Point A->B->C->D, from D it can either go directly to A or move direction in reverse.

First, let’s define the points from empty game objects. You can customize the Icons so you can see it properly from the Scene.

These waypoints will be placed in a List:

Now for the code. These are the attributes of the class:

public List<Transform> wayPoints;
public Transform currentTarget;
private NavMeshAgent _agent;
[SerializeField]
private bool _circular = true;
private bool _forward = true;
private int _currentIndex;
private bool _targetReached = false;

Initially, we want to move in the first waypoint if this exists:

void Start()
{
_agent = GetComponent<NavMeshAgent>();
if (wayPoints.Count > 0 && wayPoints[0] != null)
{
currentTarget = wayPoints[0];
_currentIndex = 0;
_agent.destination = currentTarget.position;
}
}

If it’s circular, we just need to move index back to 0 once it has reached destination in the Update() method:

if (_circular)
{
_currentIndex++;
if (_currentIndex >= wayPoints.Count)
{
_currentIndex = 0;
}
currentTarget = wayPoints[_currentIndex];
_agent.destination = currentTarget.position;
}

The output will look like this:

But if it’s reverse, you need to add direction to find if the sphere should go forward or back in the Update() method.

// If index will go out of bounds
if (_currentIndex + 1) >= wayPoints.Count)
{
_forward = false;
}
else if ((_currentIndex - 1) < 0)
{
_forward = true;
}
if (_forward)
{
_currentIndex++;
}
else
{
_currentIndex--;
}
currentTarget = wayPoints[_currentIndex];
_agent.destination = currentTarget.position;

Now the sphere can patrol in reverse:

--

--

Jaime
Jaime

No responses yet