Moving Agents on a NavMesh in Unity
Objective: How to get an AI agent to move along a NavMesh in Unity.
Moving on from the previous article where we looked at how to bake a NavMesh surface, let’s now take a look at how to get them moving along it.
Adding to the Scene Setup
From the previous scene setup, I just need to add a sphere now which is going to act as the AI agent. I have given it a new material to help distinguish the game objects:
Finally, I have added a ‘NavMeshAgent’ component to the ‘Player’ game object as shown below (which is going to handle the pathfinding along the NavMesh surface along with it’s movement):
I now need to build some code that is going to first, hold a reference to the waypoints we created and second, tell the NavMeshAgent to move to a random waypoint. Let’s also make sure to use the UnityEngine.AI namespace so we can access the NavMeshAgent class.
First things first, I know that there is a set number of waypoints so the data structure of choice is going to be an array (as this stores a fixed size). I really only need the Transform positions of these waypoints so that is going to be the data type. I am also going to [SerializeField] this array so that I can drag and drop the waypoint game objects into the Inspector fields as shown below:
Then I need a reference to the NavMeshAgent component so that we can access the ‘destination’ property within the class.
Using the New Input System, I am going to check whether the ‘Space’ key pressed and if it was, I want it to create a new _randomNumber between 0 and _waypoints.Length. This number is then going to be used as the waypoint for the agent’s destination.
Let’s take a look:
Building a NavMesh — Unity Documentation
NavMeshAgent — Unity Documentation
NavMeshAgent component — Unity Documentation
Setting Up a NavMesh in Unity — Article
“Creating a Looping NavMesh Agent in Unity”