0
0
Unityframework~5 mins

NavMesh Agent component in Unity

Choose your learning style9 modes available
Introduction

The NavMesh Agent component helps characters or objects move around a game world automatically, avoiding obstacles and finding the best path.

You want a character to walk to a target point without bumping into walls.
You need enemies to chase the player smoothly through a level.
You want NPCs to wander around without getting stuck.
You want to create automatic movement for vehicles or animals in a scene.
Syntax
Unity
NavMeshAgent agent = GetComponent<NavMeshAgent>();
agent.SetDestination(targetPosition);
Use GetComponent<NavMeshAgent>() to access the agent on your GameObject.
Call SetDestination(Vector3) to tell the agent where to go.
Examples
This moves the agent to the point (10, 0, 5) in the game world.
Unity
NavMeshAgent agent = GetComponent<NavMeshAgent>();
agent.SetDestination(new Vector3(10, 0, 5));
This checks if the agent has almost reached its target.
Unity
NavMeshAgent agent = GetComponent<NavMeshAgent>();
if(agent.pathPending == false && agent.remainingDistance < 0.5f) {
    Debug.Log("Agent reached destination");
}
Sample Program

This script moves the GameObject with a NavMeshAgent component to the position of the target Transform. It logs a message when the agent arrives.

Unity
using UnityEngine;
using UnityEngine.AI;

public class SimpleAgentMover : MonoBehaviour {
    public Transform target;
    private NavMeshAgent agent;

    void Start() {
        agent = GetComponent<NavMeshAgent>();
        if(target != null) {
            agent.SetDestination(target.position);
        }
    }

    void Update() {
        if(agent.pathPending == false && agent.remainingDistance < 0.5f) {
            Debug.Log("Agent reached the target!");
        }
    }
}
OutputSuccess
Important Notes

Make sure your scene has a baked NavMesh for the agent to navigate.

Adjust the agent's speed and stopping distance in the Inspector for smooth movement.

Use agent.isStopped = true; to pause the agent's movement if needed.

Summary

The NavMesh Agent component moves characters automatically on a navigation mesh.

Use SetDestination to tell the agent where to go.

Check remainingDistance to know when the agent arrives.