Published in


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.

  1. We need to check if there are waypoints set in the inspector
  2. If there are waypoints, then we tell the navMeshAgent to move the enemy to the _currentTarget index(which at the start will be 0)
  3. We need to know if the enemy is within a certain distance from the target waypoint then he has reached a target
  4. 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?

  1. Let’s create a bool and call is _reverse in order to allow the enemy to cycle correctly between the waypoints.
  2. 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)
  3. If he is not reversing, we increment the waypoint index
  4. 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.



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