Bird
Raised Fist0
Unityframework~10 mins

NavMesh Agent component in Unity - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - NavMesh Agent component
Start
↓
Set Destination
↓
Calculate Path on NavMesh
↓
Move Agent Along Path
↓
Check if Destination Reached
↓
Continue Moving
↓
Update Position
↓
Repeat Until Destination Reached
The NavMesh Agent moves step-by-step towards a set destination by calculating a path on the NavMesh and updating its position until it reaches the target.
Execution Sample
Unity
NavMeshAgent agent;

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

void Update() {
  if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance) {
    agent.isStopped = true;
  }
}
This code sets a destination for the NavMesh Agent and stops it when it reaches close enough to the target.
Execution Table
StepAgent PositionDestinationPath CalculatedRemaining DistanceActionAgent State
1(0,0,0)(10,0,10)Path calculated14.14Start movingMoving
2(1,0,1)(10,0,10)Following path12.73Continue movingMoving
3(3,0,3)(10,0,10)Following path9.90Continue movingMoving
4(6,0,6)(10,0,10)Following path5.65Continue movingMoving
5(8,0,8)(10,0,10)Following path2.83Continue movingMoving
6(9.5,0,9.5)(10,0,10)Following path0.71Continue movingMoving
7(10,0,10)(10,0,10)At destination0Stop agentStopped
💡 Agent reached destination; remaining distance is 0, so agent stops.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6Final
Agent Position(0,0,0)(1,0,1)(3,0,3)(6,0,6)(8,0,8)(9.5,0,9.5)(10,0,10)(10,0,10)
Remaining Distance14.1412.739.905.652.830.7100
Agent StateIdleMovingMovingMovingMovingMovingStoppedStopped
Key Moments - 3 Insights
Why does the agent keep moving even when the remaining distance is small but not zero?
Because the agent stops only when the remaining distance is less than or equal to the stopping distance (see step 6 in execution_table), not necessarily zero.
What happens if the path is not calculated yet when checking remaining distance?
The agent waits (pathPending is true) and does not move until the path is ready, ensuring smooth movement (refer to code in execution_sample).
Why does the agent stop exactly at the destination position?
Because when remainingDistance reaches zero, the agent sets isStopped to true, halting movement (see step 7 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the agent's position at step 4?
A(8,0,8)
B(3,0,3)
C(6,0,6)
D(9.5,0,9.5)
💡 Hint
Check the 'Agent Position' column at step 4 in the execution_table.
At which step does the agent stop moving?
AStep 7
BStep 6
CStep 5
DStep 3
💡 Hint
Look at the 'Agent State' column in execution_table to find when it changes to 'Stopped'.
If the stoppingDistance was increased, how would the agent's stopping step change?
AAgent would stop later, closer to destination
BAgent would stop earlier, at a larger remaining distance
CAgent would never stop
DAgent's path would change
💡 Hint
Refer to the condition in the code where agent stops when remainingDistance <= stoppingDistance.
Concept Snapshot
NavMesh Agent moves on a NavMesh towards a set destination.
Use SetDestination() to tell agent where to go.
Agent calculates path and moves step-by-step.
Agent stops when within stoppingDistance of target.
Check pathPending and remainingDistance to control movement.
Full Transcript
The NavMesh Agent component in Unity moves a game object along a path calculated on a NavMesh towards a destination. First, you set the destination using SetDestination(). The agent calculates the path and starts moving. Each update, the agent's position changes closer to the target, and the remaining distance decreases. When the remaining distance is less than or equal to the stopping distance, the agent stops moving. The code checks if the path is ready before moving to avoid errors. This process repeats until the agent reaches the destination and stops.

Practice

(1/5)
1. What is the primary purpose of the NavMeshAgent component in Unity?
easy
A. To handle user input for character movement
B. To create 3D models for characters
C. To move characters smoothly using pathfinding on a navigation mesh
D. To play animations on characters

Solution

  1. Step 1: Understand NavMeshAgent role

    The NavMeshAgent component is designed to move objects smoothly on a navigation mesh, handling pathfinding and obstacle avoidance.
  2. Step 2: Compare options

    Options B, C, and D describe unrelated functions like modeling, input, and animation, which are not NavMeshAgent's job.
  3. Final Answer:

    To move characters smoothly using pathfinding on a navigation mesh -> Option C
  4. Quick Check:

    NavMeshAgent moves objects on NavMesh = A [OK]
Hint: NavMeshAgent moves objects using pathfinding on NavMesh [OK]
Common Mistakes:
  • Confusing NavMeshAgent with animation or input components
  • Thinking NavMeshAgent creates models
  • Assuming NavMeshAgent handles user controls
2. Which of the following is the correct way to set a destination for a NavMeshAgent named agent in C#?
easy
A. agent.MoveTo(new Vector3(10, 0, 5));
B. agent.Navigate(new Vector3(10, 0, 5));
C. agent.GoTo(new Vector3(10, 0, 5));
D. agent.SetDestination(new Vector3(10, 0, 5));

Solution

  1. Step 1: Recall NavMeshAgent method for destination

    The correct method to set a destination is SetDestination, which takes a Vector3 position.
  2. Step 2: Check method names

    Methods like MoveTo, GoTo, and Navigate do not exist on NavMeshAgent.
  3. Final Answer:

    agent.SetDestination(new Vector3(10, 0, 5)); -> Option D
  4. Quick Check:

    SetDestination sets target position = B [OK]
Hint: Use SetDestination with Vector3 to move NavMeshAgent [OK]
Common Mistakes:
  • Using non-existent methods like MoveTo or GoTo
  • Forgetting to use Vector3 as parameter
  • Confusing SetDestination with transform.position
3. Given the code below, what will be the output in the Unity Console?
using UnityEngine;
using UnityEngine.AI;

public class MoveAgent : MonoBehaviour
{
    public NavMeshAgent agent;

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        Vector3 target = new Vector3(5, 0, 5);
        bool result = agent.SetDestination(target);
        Debug.Log(result);
    }
}
medium
A. True
B. False
C. NullReferenceException error
D. No output

Solution

  1. Step 1: Understand SetDestination return value

    The SetDestination method returns true if the destination is valid and reachable on the NavMesh.
  2. Step 2: Analyze given target and agent

    The target (5,0,5) is a valid position assuming the NavMesh covers it, so SetDestination returns true and logs it.
  3. Final Answer:

    True -> Option A
  4. Quick Check:

    SetDestination success returns true = C [OK]
Hint: SetDestination returns true if path is valid [OK]
Common Mistakes:
  • Assuming SetDestination returns void
  • Expecting false without checking NavMesh coverage
  • Ignoring possible NullReference if agent not assigned
4. What is wrong with the following code snippet that tries to move a NavMeshAgent?
public NavMeshAgent agent;

void Update() {
    Vector3 destination = new Vector3(10, 0, 10);
    agent.SetDestination(destination);
}
medium
A. SetDestination requires a NavMeshPath parameter
B. Calling SetDestination every frame can cause performance issues
C. NavMeshAgent must be moved using transform.position
D. The destination vector is invalid

Solution

  1. Step 1: Review usage of SetDestination in Update

    Calling SetDestination every frame is unnecessary and can cause performance overhead because the agent recalculates path repeatedly.
  2. Step 2: Check other options

    The destination vector is valid, NavMeshAgent should not be moved by transform.position, and SetDestination takes a Vector3, not NavMeshPath.
  3. Final Answer:

    Calling SetDestination every frame can cause performance issues -> Option B
  4. Quick Check:

    SetDestination in Update causes overhead = D [OK]
Hint: Avoid calling SetDestination every frame; call only on target change [OK]
Common Mistakes:
  • Moving agent by changing transform.position directly
  • Passing wrong parameter types to SetDestination
  • Ignoring performance impact of repeated calls
5. You want a NavMeshAgent to move to a target only if the path is valid and complete. Which code snippet correctly checks this before moving the agent?
NavMeshPath path = new NavMeshPath();
Vector3 target = new Vector3(7, 0, 7);

// Which code is correct?
hard
A. if (agent.CalculatePath(target, path) && path.status == NavMeshPathStatus.PathComplete) { agent.SetDestination(target); }
B. if (agent.SetDestination(target)) { agent.CalculatePath(target, path); }
C. agent.SetDestination(target); if (path.status == NavMeshPathStatus.PathComplete) { // do nothing }
D. if (path.status == NavMeshPathStatus.PathPartial) { agent.SetDestination(target); }

Solution

  1. Step 1: Understand path calculation and status check

    Use CalculatePath to check if a path to the target exists and is complete before setting destination.
  2. Step 2: Analyze each option

    if (agent.CalculatePath(target, path) && path.status == NavMeshPathStatus.PathComplete) { agent.SetDestination(target); } correctly calls CalculatePath and checks path.status before SetDestination. Others either call methods in wrong order or check wrong status.
  3. Final Answer:

    if (agent.CalculatePath(target, path) && path.status == NavMeshPathStatus.PathComplete) { agent.SetDestination(target); } -> Option A
  4. Quick Check:

    CalculatePath + PathComplete check before SetDestination = A [OK]
Hint: CalculatePath and check PathComplete before SetDestination [OK]
Common Mistakes:
  • Calling SetDestination before checking path validity
  • Ignoring path.status or checking wrong status
  • Confusing CalculatePath and SetDestination roles
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard