NavMeshAgent
- Game Development course
- Advanced
- Lesson 38/71
- 4 min
Learn enemy movement with the NavMeshAgent component.
The NavMeshAgent Component
The NavMeshAgent component is attached to characters (enemies, NPCs, companions) intended to navigate the NavMesh. It handles path resolution, acceleration, and dynamic steering around obstacles.
using UnityEngine.AI;
public class EnemyMovement : MonoBehaviour {
private NavMeshAgent agent;
void Awake() {
agent = GetComponent<NavMeshAgent>();
}
}Upon instantiation, the agent automatically snaps to the closest underlying NavMesh surface.
Agent Parameters and Obstacle Avoidance
The NavMeshAgent exposes critical movement controls: speed (maximum velocity), stoppingDistance (braking proximity to target), and radius (collision cylinder width).
agent.speed = 3.5f;
agent.stoppingDistance = 1.0f;When agents meet, built-in Obstacle Avoidance routines steer them around one another instead of clipping through.
Practice Agent speed configuration
Define a Start method. Inside, declare float hiz = 3.5f; and print "Agent hizi: " + hiz to the console using Debug.Log.
Starter code
using UnityEngine;
public class AgentSpeedTester : MonoBehaviour
{
// Start icinde hiz degiskenini tanimla ve yazdir
}Sample solution
using UnityEngine;
public class AgentSpeedTester : MonoBehaviour
{
void Start()
{
float hiz = 3.5f;
Debug.Log("Agent hizi: " + hiz);
}
}Expected output
Agent hizi: 3.5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which component grants a character the ability to pathfind and steer around obstacles on a NavMesh?
- MeshFilter
- BoxCollider2D
- NavMeshAgent Correct answer
- AudioReverbZone
Explanation: The NavMeshAgent component enables characters to traverse toward destinations across the NavMesh without colliding into obstacles.
2 Get Agent component
NavMeshAgent agent = GetComponent<____>();
NavMeshAgent agent = GetComponent<NavMeshAgent>();
Explanation: To retrieve the NavMesh navigation component in script, 'GetComponent<NavMeshAgent>()' is called.
3 Agent component properties
| Term | Meaning |
|---|---|
NavMeshAgent |
AI movement component tracking path |
speed |
Maximum locomotion speed of the agent |
stoppingDistance |
Stopping distance before destination |
obstacle avoidance |
Characters steering around each other |