Unity : AI [Navmesh implementation (Part III)]
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.
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
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
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!