SetDestination
- Game Development course
- Advanced
- Lesson 39/71
- 4 min
Learn to walk to a target with SetDestination.
Moving to Destination with SetDestination
To instruct an agent to navigate toward a 3D coordinate, agent.SetDestination(targetPosition) is invoked. The agent computes the optimal path and begins movement.
using UnityEngine.AI;
public class Chaser : MonoBehaviour {
public Transform target;
private NavMeshAgent agent;
void Update() {
agent.SetDestination(target.position);
}
}As the target displaces (such as a running player), re-issuing the destination updates the pursuit trajectory.
Arrival Check and remainingDistance
To verify whether the agent reached its objective, the agent.remainingDistance property is evaluated against stoppingDistance.
if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance) {
// Destination reached
Debug.Log("Hedefe ulasildi");
}Checking agent.pathPending ensures the path is fully resolved before evaluating arrival distance.
Practice Target distance check
Define a Start method. Inside, declare float kalanMesafe = 0.5f; and print "Kalan mesafe: " + kalanMesafe to the console.
Starter code
using UnityEngine;
public class DestinationTester : MonoBehaviour
{
// Start icinde kalanMesafe tanimla ve yazdir
}Sample solution
using UnityEngine;
public class DestinationTester : MonoBehaviour
{
void Start()
{
float kalanMesafe = 0.5f;
Debug.Log("Kalan mesafe: " + kalanMesafe);
}
}Expected output
Kalan mesafe: 0.5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method assigns a new 3D target coordinate to a NavMeshAgent to initiate navigation?
- agent.SetDestination(target) Correct answer
- agent.MoveInstantly(target)
- agent.TeleportTo(target)
- agent.JumpToPath(target)
Explanation: The SetDestination method calculates a path across the NavMesh toward the supplied Vector3 position and begins traversal.
2 Set target destination
agent.____(target.position);
agent.SetDestination(target.position);
Explanation: The 'SetDestination' method is invoked to assign the agent's destination coordinate.
3 Navigation tracking properties
| Term | Meaning |
|---|---|
SetDestination |
Sets destination and calculates path |
remainingDistance |
Remaining distance to destination |
pathPending |
Whether path is being computed |
hasPath |
Whether the agent has an active path |