Welcome to part 1 of the Pathfinding in Unity tutorial series. In this series we’re going to be looking at how we use the navigation tools built into the Unity engine. Navigation is one of the most critical aspects of getting a non-player character behaving in a video game. Given we want them to be reliable and explore the world without any real issues. Fortunately, video game engines often provide their own navigation tools in order to speed up this process. This tutorial series will run across a number of chapters, as we first explore how to build the most critical part of this toolset: the navigation mesh or navmesh, how to make a character move upon it, then run basic patrols, dynamically place characters onto navmeshes, build navmeshes at runtime and much more. In this first tutorial, we’re going to focus on how to get a navmesh working, followed by how to get a player to move towards a fixed location on that navmesh.
So first-up let’s talk setup, I’m running the following tools as part of this tutorial:
Many of the initial features I am working with in these earlier tutorials appear in other releases of Unity 5. However, in later tutorials – where I’m doing dynamic navmesh baking – you’ll need to be running on Unity 5.6 or above. As a general rule, I’d try all of this out in it’s own separate project and then migrate it over to your games you’re working on. I’d avoid upgrading your game to a new version of the engine unless you absolutely have to as it can cause all sorts of headaches for you.
In addition, this tutorial series expects you to have a working understanding of both the Unity game engine as well as C# programming. If you’re new to one or either of these, you can check out my tutorials on C# and Unity for Beginners respectively on the AI and Games YouTube channel.
Creating a Surface for Navigation
So with a starting project in place, my first port of call is to create the navigation mesh. The navigation mesh is a data structure that is calculated from a surface or area that we want our character to move on. We can apply this to a variety of meshes we have in a given scene in order to declare them as traversable.
So let’s start by creating a basic surface upon which we can create a navigation mesh. Create a plane game object in the editor (right-click>>3D Object>>Plane) and place it at the centre of the world with a transform of 0,0,0. We can also increase the scale of the transform to make that plane a little bit bigger. I’m going to make it 5,5, 5, though given it’s a plane increasing the scale on the y has a negligible effect.
The Navigation Tab
Alright, with that in mind, let’s create the navigation mesh. To do this, head into the Windows>>Navigation menu and this will create a small tab next to the inspector which is the navigation tab. In here, we can bake the navmesh as well as make important settings that will influence how an agent – which is a character that moves on the mesh – will explore that space. Working from left to right, we’ll look at each part of the navigation tab.
- Agents: This allows us to define different types of agents that will be able to walk across the navmesh. For now, we’re only going to have one. But we can customise aspects of it’s shape as well as the maximum height of steps and slopes it can navigate.
- Areas: Here we can define specific tags that are used for parts of the world. Perhaps more importantly, we can attribute costs to them as well. This allows us to create areas of the map that are deemed less desirable to walk across, like say we’re walking through water or sand where it will slow us down, we can make that more expensive.
- Bake: This is where we bake the actual navigation mesh of the environment and set the default settings used to bake that mesh.
- Object: Allows us to filter the scenes in the Hierarchy view such that we can identify parts that are deemend part of the navigation and terrain. More importantly, we can set an object as being navigation static, which is needed for it to be used in the navigation system.
- We will be returning to many of these features in future tutorials, but for now, I will be focussing on the Bake and Object tabs. With these alone we can build a basic navigation mesh.
Building a Navigation Mesh
So let’s start by going into the Object tab, followed by selecting the plane that we have in the inspector. You’ll note that the plane is now highlighted in the Navigation tab. Next we click ‘Navigation Static’, which tells us we want to declare this space as part of the navigation space and it’s not going to change it’s position or move. We kind of want that otherwise the navigation mesh would not be accurate as the plane moves. In addition, it would mean we’d need to recalculate the navmesh every frame to compensate. But we’ll deal with that in a future tutorial.
With it navigation static box ticked, next we head back into the Bake tab. Now for the purposes of this example, we don’t really need to worry about the settings and can leave them as they are. However this will prove more useful in later tutorials as we begin to dictate whether an area is too tight or too high for an agent to move through. For now though, let’s leave these settings as they are and press the Bake button.
Now if all has went according to plan, you’ll note in the scene view that the plane now has a blue-ish square being drawn over it. Voila! We have a navmesh. It’s not terribly exciting. But we’re going to have something drive on it next.
Creating a Navigation Agent
With the navmesh in place, our next job is to build the navigation agent. A navigation agent is an object that can move around the environment using a navigation mesh. So we’re going to create just a basic Unity cube and then make that the navigation agent.
So let’s create a new cube over in the hierarchy view (Right-Click, 3DObject>>Cube) and place it in the centre of the map at (0,1,0) transform – slightly off the ground. Then rename it to NPC by either clicking F2 when you’ve selected it in the hierarchy or by Right-click >> Rename. Now if you want you can change the colour of that cube using a base material in order to differentiate the player from the floor. I’ve elected to do that courtesy of a basic material with the albedo set to red.
Now we go into the inspector view and click Add Component. You can then add the required component in one of two ways:
- Use the menu and Click Navigation >> Nav Mesh Agent
- Or just type Nav Mesh Agent into the search bar.
With your agent added, it’s all ready to go and move around the map. The thing is, it doesn’t actually move. And that’s because you still need to actually call the navmeshagent component to tell it to do stuff. For that, we need C# code!
Moving a Navigation Agent
Let’s start this segment by creating a C# class (or script as it is known in Unity) in the Project view. Click the Create Button >> C# Script and call it ‘NPCMove‘. This is our non-player character or NPC and I’m going to use the navmesh to move them.
So once it’s created, open up your code editor – which in my case is Visual Studio 2017 – and write your code such that it looks like that shown below:
So this requires a base level of understanding of Unity itself, but in the Start method I am grabbing a reference to the nav mesh agent component we just added to our NPC character. In addition, I then run a check to ensure it is not null and that we have actually found that reference. In the event we found the navmeshagent successfully, I then set the destination. The destination is based on a transform variable that I have exposed in the Unity editor by using the SerializeField command. Now if that isn’t null, I get the position from that transform and set it as the destination in the navmeshagent.
So quickly compile the code (Build >> Build Solution or Ctrl + Shift + B) and back into Unity!
Bringing It To Life
So with this all done, we have two small steps left and it’s ready to go!
First, add the NPCMove class as a component of your NPC game object. You can either use the Add Component area on the bottom of the game object in the inspector, or just drag the NPCMove class onto the object itself. Provided you code has compiled correctly it should now appear in the inspector view. Now you’ll note that the destination variable is visible but it says ‘None’ right now. Meaning we need to give it a destination.
So next up, let’s create a game object to move towards. Right-Click in the Hierarchy and select 3D Object >> Sphere. Now let’s place it somewhere on that surface, or just above it (give it a Y value of 1). Rename it to ‘Destination’ and if you want change it’s colour too. I elected to give it a blue colour.
Lastly, click the NPC then drag and drop the Destination object into the _destination transform on the NPC. It should then fill that variable and refer specifically to the Destination game object.
With that done, go ahead and click play! And boom, our little cube moves over to the sphere and then stops when he overlaps with it! Awesome.
So in this first tutorial we’ve learned how to setup the navigation mesh and have a character move within it. Feel free to play around with this environment and change the shape of it, but remember the need to build the navmesh after you change all this stuff. In part 2 we’re going to look at how to add obstacles to the environment in order to make it more interesting, followed by part 3 where we start creating a NPC that can patrol to multiple navigation points.
This has been part 1 of the Unity Pathfinding tutorial series here on AI and Games. A series that is supported thanks to my sponsors over on patreon.com/ai_and_games. If you like this tutorial or any of the case studies, AI 101, video essays and more that I do here, please consider supporting me to continue to make more content.