Moving Agents on Navmesh
Objective: Move AI to way-points in the scene.
In the last article, I added a Navmesh and a NavMeshAgent onto the AI. I’ll go over on how to use the NavMeshAgent to move the AI and to move along the waypoints and even reverse it when it gets to the last one. To start open the AI script and add the library UnityEngine.AI;.
Next will be to create a Transform List to hold all the way points. Will need to track the currentTarget with an int, and grab the NavMeshAgent to move the AI and finally a bool to know if we are going to the last waypoint or back to the beginning. This is optional but for my AI I want them to back backwards.
In Start we will need to grab the NavMeshAgent with GetComponent, than null check it. Next, use _navMeshAgent.destination and assign it the first transform in the list by giving it the 0 place. The reason for _waypoints[0].position is because destination takes in a vector3 and not a transform.
For more on different NavMeshAgent methods refer to:
In Update we will check the remainingDistance and if is less than 1f, check to see if we are going in reverse or not. Than we SetDestination with _waypoints[currentTarget].position.
If we are not going in reverse we will move to the ForwarMarch. In ForwardMarch we will see if the current target is equal to length of the list -1. There are 6 Transform but with List we only use 0 to 5. That is why we use -1. If is set isReversed to true and if it is not add one to the currentTarget.
Same thing for BackwardsMarch except we check to see if we are at zero. If we are set isReversed to false. If we are not subtract one from the Current Target.
Now all that’s left to do is assign the points to the waypoints.
With this we can have our AI move now.
Thank you for reading!! Have a wonderful day!