Waypoint system for enemy movement
Objective: Create a modular waypoint system for enemy movement in Unity.
Focusing on the first SecurityGuard, create three waypoints which contain only the transform component. One way to set these transforms is to move duplicates of the guard, Ctrl + D, and reposition them in the scene view. Rename them Point_A-C, as shown below. Unpack these prefabs and delete everything, including child objects, except the transform.
Add Nav Mesh Agent component to all SecurityGuards.
Create a GuardAI C# script and attach it to all guards. This script will need a list of _wayPoints, an int variable to store the _currentWayPoint, _agent variable for the Nav Mesh Agent, and a bool to _reverse the direction of movement. Assign the _agent using GetComponent<NavMeshAgent>() and null check it. Now assign the SecurityGuard’s _wayPoints list using the inspector, as shown above.
Within void Update() of the GuardAI script, check to see if the guard has a path assigned, _agent.hasPath, or pending, _agent.pathPending. This avoids distance calculations. Next check to see if the Guard is at the beginning of the path, i.e. _reverse is false. Likewise check to see if the guard is at the end of the path, i.e. _reverse is true, but only if there are more than one _wayPoints.
Now knowing the direction to move along the path, the _currentWayPoint, is incremented either up or down, see below. If the new way point is not null then the Nav Mesh Agent is updated using _agent.destination.
Below we can see the first guard moving back and forth along the defined path.
This article uses assets from The Great Fleece by GameDevJon on the Unity Asset Store.