Unity : AI [Navmesh implementation (Part III)]

Matteo Lo Piccolo
3 min readJan 17, 2022

At this point we have the AI that can walk to one point randomly.
But what we want to do is make the Ai goes from point A to B, C, D, E and at end go towards F point.
And restart its path.

We have already o good part of implementation, for example the reference to all points.

P.S. the order of path is the same of the order inside the List<>, if we change inside the List<> in the editor the order changes.

For this example we take the linear order.

To create this behaviour, the first thing we need is to check WHEN the AI arrive at point, right?
And when it arrives at one point can move to another point.

This is what we need, remainingDistance
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-remainingDistance.html

This property returns exactly the distance from the AI and the point.
If we try to Debug.Log() the distance between AI and the first point we see the result in the console

I use _points[0].position because is the point A, but for testing is ok to use any point you want

Perfect. Now if we want the AI stop we can use a simple check

This works fine, to make the AI moves to another point, the idea at the base is something like this

SetDestination() reference
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.SetDestination.html

Good!
But obviously we need to “modular” this code, we can’t literally write something like this for every point.

The logic is to go to the point A, then update the index, go to point B, update the index and go to point C etc.
So we need a variable that contain the currentPoint

Set it to 0, and pass it inside _points[_currentPoint].position

In the Update() we upadte the currentPoint

If it’s more readable

Both codes ar the same.

Test it

And it works perfectly, but at the end we have an error.
Why?
Because in the If Statement the condition is true again, but we don’t have any other points, and Unity give us an ArgumentOutOfRangeException.

In the next article we fix the problem, meantime try to see if you can resolve it to yourself, it’s a good exercise!

--

--

Matteo Lo Piccolo

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!