In this article I’ll demonstrate how to set up a modular guard AI. We’ll be using 1 script for all three guards. Lets get into it!
Here you can see, I’ve added a NavMesh Agent as a script called Guard AI to the security guard prefab. In the script I’ve created a List of transforms that we are using as waypoints. I also have an empty game object to hold my waypoints. I’ve placed these in specific places on the game board. I’ve found the easiest way to make these is by copying the security guard object and dragging it to the appropriate location, then delete all the meshes, models, etc. We are going to be measuring the distance between the security guard and the waypoint so having a similar transform is ideal.
Lets focus on the 1st security guard. The idea is this:
We want them to idle at the beginning and end of their waypoints.
Here is the script. Lets break it down.
In Update we have this:
wayPoints is our List<transform> variable. This is what holds the waypoint’s transform information. We also have currentTarget as an int variable. We are going to increment through the list with this.
SO if our wayPoints.Count > 0 and the currentTarget isn’t null we are going to SetDestination to the currentTarget.position. Easy right? We did this pretty much with our player movement script using the Nav Mesh.
Next we are calculating our distance from the guard’s position to the waypoint.
We need a bool to tell us whether we have reached our target or not. I called mine “targetReached”. We want to set this to true when we reach the target or when our distance from the target is less than 1. Thats what is happening here:
We start a coroutine once we set this to true. Our coroutine looks like this:
This is where we are pausing when we reach the beginning and end of our List of waypoint Transforms. Then we have a reverse bool that tells us whether to increment up or down. SO if currentTarget == 0 we are going to set reverse to false aka increment up. When we reach the wayPoints.Count we set it to true and increment down. This sets our destination to the currentTarget causing the guard to turn around when necessary.
We have our guard set up moving to the desired waypoints! Now all that is left to do is change our animation states from idle to walking. I’ll dig a little into that in the next article. For now go ahead and add the waypoints to your other security guards. The second one is going to stay in one place. The 3rd one will have 4 waypoints. The end result should show them all walking to and from the waypoints! :)