Creating Modular Waypoint System in Unity (part 2)
Objective: Write the code to make the guard move through the waypoints.
In the GuardAI script I defined different variables. A list of transforms to store the different waypoints for the guard movement, an int variable to have the index of the current target where the guard have to move, a variable called path to increase or decrease the current target index and the nav mesh agent.
In the start function we initialize the nav mesh agent and check if the guard has waypoints to set the first destination.
Then in the Update function we first check if the guard has waypoints assigned, in another if statement we check if the distance to the destination is less than 1.
The idea is when the guard reaches the target we have to set the next waypoint, but before that we check if the current index is equal or less than 0 to assign 1 or if the current target is equal or greater than the waypoint count minus 1 to assign -1 to the path variable.
Once we calculate the path we just add it to the current target variable and set the new destination.
And that’s it!!! The guard is going to move between waypoints.