Tip of the Day: Modular AI Waypoint System in Unity3D
Many times in your games you want your enemies to patrol in a certain area between two or more points and maybe have them stop a little bit before moving on to the next waypoint.

Let’s see how we can achieve this!
First off, let’s start by creating a new C# script for Enemy AI that will be responsible for moving your enemies. (This method will depend that your game is using a Nav Mesh in your level and a nav mesh agent on your enemies.)
Now get hold of the NavMeshAgent and create a list that will hold the waypoints.
[SerializeField] private List<Transform> _waypoints;NavMeshAgent _agent;private void Awake()
{
_agent = GetComponent<NavMeshAgent>();
}
Also let’s create an int “_currentTarget” and set it to 0. This will represent the index of the list we created. So at the start, the current waypoint index is 0 which is the 1st waypoint.
private int _currentTarget = 0;
Let’s think about the logic that we will apply in the Update method.
- We need to check if there are waypoints set in the inspector
- If there are waypoints, then we tell the navMeshAgent to move the enemy to the _currentTarget index(which at the start will be 0)
- We need to know if the enemy is within a certain distance from the target waypoint then he has reached a target
- We need to know what is the next waypoint

In order to know the next waypoint, we will create a coroutine “WaitBeforeMoving”. What is the logic here?
- Let’s create a bool and call is _reverse in order to allow the enemy to cycle correctly between the waypoints.
- If the AI is the first and last points, we make him wait a little (you can change this if you want to make him stop at every point)
- If he is not reversing, we increment the waypoint index
- If he is reversing, we decrement the waypoint index.


From here you can easily extend this method to have an alerted state for example or basically anything you want. This is just the backbone.