Unity : AI [Navmesh implementation (Part II)]

Matteo Lo Piccolo
4 min readJan 14, 2022

After we set up the Scene, it’s time to create our AI.
I create a sphere.

I even create a material and apply to it.

What we want is make the AI to move from point to point in a “path”.

The first step, is add a component to the sphere to tell it what surface is a Navmesh and where can “walk”.
The component is NavMesh Agent
Here’s the reference
https://docs.unity3d.com/Manual/class-NavMeshAgent.html
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.html

Thanks to this component, many variables we need to move the AI like Speed, Acceleration, Stopping Distance, are already incapsulate here.

If we focus on the AI we see the component is similar to a Collider and is wrapped around it.

Is the green cylinder

Now that we have everything set up, we need to understand how use this implementation to make the AI moves from point to point.

Obviously we need a script, i called it AI, and we attach it to the sphere.
We open it and try to figure out what we need

If we need to walk from point to point, in a linear way or randomic way, in any case we need a reference to that points.
Than we need our friend, Google, and search to how move navmesh Agent to a destination

Reference to the link above
https://docs.unity3d.com/Manual/nav-MoveToDestination.html

After we read this information, we can set up our code.
For the points I use a List<> but we can use even an Array[].

And now we have to take the reference to our component NavMesh Agent

Little shortcut : if we try to take the reference to the NAvMEsh Agent, this is what happen

We have a sort of error, because to use NavMesh we need UnityEngine.AI.
If we press Alt+Enter over NavMesh

Intellisense open a menu and we can add the using statement.
Nothing crazy, a simple shortcut.

Now, for a simple test, we can try this in Start() :

I try to explain what is it.

We cash the NavMesh component, then we make a simple check.
If the component is not null, what we have to do.
We need to move right?

So as we read in the documentation, we use the destination property

which set the destination of the agent in world-space units.

And what is the destination. One of the points.
So we “set” the destination to a Random point in our List<> of points.
And we finish with .position at the end, because we have a List<> of Transform but destination ask us a Vector3.

To write it better, we can create a variable that store random position

NOTE : remeber to pass the waypoints in the Inspector

If we test it

In the next article we continue to use NavMesh in different ways!

--

--

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!