Working with NavMesh Agents

Tutorial

·

Beginner

·

+10XP

·

15 mins

·

(304)

Unity Technologies

Working with NavMesh Agents

Once a NavMesh has been baked for the level it is time to create the elements which can navigate the scene. In this tutorial, you will learn to use a NavMesh Agent component and create a simple script.

Languages available:

1. Working with Navmesh Agents

A NavMesh is a designated mesh in your Unity scene, which specifies navigable areas in your environment, including areas where characters can walk, as well as obstacles. This is useful for scenarios which incorporate pathfinding and AI-controlled navigation. The NavMesh Agent component helps characters to avoid each other, move around the scene toward a common goal, or any other type of scenario involving spatial reasoning or pathfinding.


Once a NavMesh has been baked for the level, it is time to create a character which can navigate the scene. This is done using a NavMesh Agent Component and a simple script.


2. Adding a NavMesh Agent Component

1. Select the Character in the Hierarchy window.


2. In the Inspector, select the Add Component button, and select Navigation > Nav Mesh Agent (Figure 01).


Figure 01: Nav Mesh Agent Settings

Figure 01: Nav Mesh Agent Settings


3. Scripting the Movement

1. Create a new C# script and name it ‘MoveTo’, and attach it to your character.


2. Double-click on the MoveTo script


3. Add the following code to the script


[@portabletext/react] Unknown block type "code", specify a component for it in the `components.types` prop

4. Save the script.


5. Create a new Empty GameObject, and rename it to ‘Goal’.


6. Place the Goal GameObject to a location somewhere in your scene within the baked Nav Mesh.


7. Select your character, and within the MoveTo Component, set the Goal in the component field to your Goal GameObject (Figure 02).


Figure 02: the Move To script component’s Goal object.

Figure 02: the Move To script component’s Goal object.


8. Press Play and watch the character move to the goal


4. Conclusion

NavMesh Agents can be configured to create different pathfinding behaviors based on the character types you have in your projects. Try configuring the NavMesh Agent to create an alternate behavior.


Complete this tutorial