Let’s carry on adding to your script:
1. Your Ghost needs to move on to the next waypoint when it reaches the last one it had set as its destination. The easiest way to track which waypoint is next is by storing the current index of the waypoint array.
Below the waypoints array declaration, add the following code:
2. Next, let’s move on to the Update method so you can use this index.
In the Update method you need to perform a check — you want to know if the Nav Mesh Agent has arrived at its destination. An easy way to check this is to see whether the remaining distance to the destination is less than the stopping distance you set in the Inspector window earlier.
Add the following if statement to the Update method:
3. Now you need to update the current index, and then use it to set the Nav Mesh Agent’s destination. To do this you will use a new operator called the remainder operator which is represented by the percentage character: %.
Add the following code within the if statement:
The remainder operator takes whatever is to its left and divides it by whatever is to its right, then returns the remainder. For example, 3 % 4 would return 3 (because 4 goes into 3 zero times with 3 left over). 5 % 4 would return 1 (because 4 goes into 5 once with 1 left over).
Your code is saying, “Add one to the current index, but if that increment puts the index equal to the number of elements in the waypoints array then instead set it to zero.” It would be set to zero in this circumstance, because the remainder when dividing any number by itself is zero.
4. Now that you have incremented the index (and looped it back to zero when necessary), you need to use it. Add the following below the index incrementation:
This is exactly what you did in the Start method, except instead of using zero as the index, you’re using whatever waypoint the Ghost is currently up to as the index.
5. That’s it! Your completed script should look like this:
6. Save the script and return to Unity Editor.