Creating Modular Waypoint System in Unity
Now that we know how to move our Player, it’s time to use Navmesh to move our Enemy. We will make a modular waypoint system to create a path our enemy can patrol.
First, let’s create our scene and bake the navmesh. Create a simple scene. I used a Plane as a floor and few cubes that scaled for obstacles. Remember to change all of them to static.
Go to Window ->AI -> Navigation, go to the bake tab, and click on the Bake button.
Create waypoints you want your enemy to follow. To do that use empty GameObjects. Name them appropriately.
To create an icon for your waypoints, add an image in the Assets ->Gizmos folder, and create a new script and add this simple method.
Create an Enemy. I used a simple capsule for this example. Add a NavMesh Agent component to your enemy.
Create an EnemyAI script and attach it to the Enemy GameObject. Create a new variable called waypoints and add all the waypoints in the Inspector..
Create Navmesh variable and access this component in the Start() method.
Add two new variables. currentTarget will tell us what waypoint is our current target, and the reverse will be changed to true if we go through all the waypoints and our enemy needs to go back to the beginning.
Now in the Update method, first we will check if our list is not empty, and if the current target we are looking for is not null. Then we will set a destination for our enemy. The next step is to check how far away is our enemy from his current target. If it is < 1.0f, then our enemy is at his destination and needs to go to the next waypoint. We need to check if the “reverse” is true to know which way our enemy is going. If it is true, we will subtract one from the currentTarget. If currentTarget is 0, then we are at the start and need to change reverse back to false.
If we check and the reverse is false then we need to add one to the currentTarget. If currentTarget is the same as the number of waypoints, then it means that we are at the last waypoint. We need to change reverse to true and subtract from currentTarget.