Creating a modular waypoint system in Unity
Objective: Create a waypoint system that can be used by multiple guard objects but using the same script
Above you can see the navmesh waypoint system in action with the guard. I first had to create the waypoints that I wanted the guard to follow. I have an empty game object in the scene and then added an empty child for the first guard. I then put my waypoints in the position I wanted in the scene and then dragged them to be children of the first guard in the waypoints object.
Now comes the making of the modular system.
First I created a few variables to help. The navmesh agent, a list of transforms for the waypoints, the currentTarget and a bool to tell if I need to reverse the count through the waypoints.
To make sure that I do not get a null reference error if the script is attached to a guard that does not have a waypoint to move towards. I do this by making sure that the waypoint count is bigger than zero and that the currentTarget is not null.
If these checks pass then the agent moves to the next position in the waypoints list. I then do the same distance check as with changing the player animations.
If reverse is true that means that the guard is at the end of the waypoints list and needs to turn around and go the other way. I then decrement the currentTarget variable. If the currentTarget = 0 then the guard has reached the first waypoint in the list and they now need to turn around and go back up the waypoints. I then set reverse to false and set the currentTarget = 0;
The next run through of the waypoints will mean that reverse is false and it will run the else statement. Which does the reverse of the above.
This allows me to create a system that will allow each guard to have a different number of waypoints and still use the same script for all of them.