Journal 68 — “The Great Fleece” Guard AI Setup in Unity
Objective: To add the first security guard AI movement and waypoints
In “The Great Fleece”, we just implemented the player movement, the camera movement to follow the player, and the basic walk and idle animations. Now we want to add the guard AI.
In the game, the guards can move along paths between the display cases. We can create a single C# script that can control the movement for all three guards. In it, we can add a List<Transform> wayPoints variable to store waypoints. The size of the list can vary from 0 to as many different waypoints you would like to choose.
The security guards all need to use the Navmesh Agent like the player.
For the first security guard, we can duplicate the guard and move the copies to the two waypoints. Also for the two copies, remove the guard C# script and Navmesh Agent so they don’t affect the game. We can then update the security guard waypoints in the Inspector.
One additional edit to the Points A and B we previously created. Now that we have them correctly positioned, we want to delete the prefabs which leaves un an empty waypoint object. In Unity 2021, we need to right-click and unpack the game objects before deleting.
Next, we need to update the C# script to create a new Transform variable for the current waypoint target as wayPoint. In order to avoid a null reference exception error, we need to include a null check to check for two conditions: those guards that have no waypoints and sit idle, and those guards that have not had wayPoint. We can test the results in Playmode.
Let’s update the code similar to the player script, where we have a reference to the NavMeshAgent and use SetDestination to the currentTarget.position.
Seeing this in action, the security guard chose the shortest path and moved into the other guards paths, so we need to modify the code to add an intermediate waypoint to avoid this.
Waypoint Cleanup 1
We can add another waypoint in Unity and rearrange the points. Also we need to update the security guard waypoints in Unity Inspector.
Let’s make a quick test in the C# script Update method to move the guard from Point A to Point B to Point C. Then we can fix the code to make it more modular for any guard. Basically if the waypoint distance is less than 1, we want to advance to the next waypoint.
Waypoint Cleanup 2
Let’s clean the code up by making an integer to store the waypoint position.
We can create a bool to check whether to reverse the count, and use a series of if-then statements to increment and decrement the index if the index equals the wayPoints.Count, and also check if the index equals 0.
Finally, here is the working waypoint system for the first security guard. We will fix the other security guards in a later article.
Thank you for your time!