Objective: To get an AI agent setup to loop through a series of waypoints and return via the same route (in reverse).
So far we have created the NavMesh surface, added the AI Agent to our project and got them automatically moving between random waypoints.
Now, I would like to use the linear path of waypoints I created and to have the AI Agent move through them sequentially, ultimately hitting the last waypoint and then returning in reverse, creating an endless loop.
E.g. Waypoints : 0 → 1 → 2 → 3 → 4 → 5 → 4 → 3 → 2 → 1 → 0.
The project is already setup, so let’s just build some code!
To get started — Make sure we are using the UnityEngine.AI namespace so we can access the NavMeshAgent class.
Then I am going to need a variable to keep track of the _currentWaypoint and also a bool toggle to tell the AI Agent that it is now moving along a reverse path.
I need to get a reference to the NavMeshAgent component so that I can access some built-in properties such as — ‘destination’ and ‘remainingDistance’.
Lastly, as already previously setup in another article, I have an array of waypoints that have been allocated in the Inspector.
Now, let’s build some logic for the AI Agent that is going to check whether the remaining distance between the AI Agent and the destination position is less than 0.25f, and if it is, we are going to either increase or decrease the ‘_currentWaypoint’ value depending on whether the AI Agent is moving forwards or in reverse (code shown below).
The AI Agent will then automatically move to it’s next destination.
Let’s also create some if checks to make sure that our AI Agents destination range doesn’t exceed the total waypoints otherwise we will receive the index out of bounds error!
When the AI Agent’s ‘_currentWaypoint’ equals the waypoints array length (which in my case is 6 less 1, because arrays start at a 0 value index), call the trigger bool to move the agent in reverse.
“Using a Finite State Machine to Create Smart AI in Unity”