Challenge 2: NavMesh target
- Game Development course
- Advanced
- Lesson 68/71
- 5 min
Write a script that calls NavMeshAgent.SetDestination.
Challenge 2: Setting NavMesh Destination
To enable AI characters to pathfind across 3D scenes, the NavMeshAgent component is utilized. Invoking SetDestination directs the agent toward the target position.
using UnityEngine.AI;
NavMeshAgent agent = GetComponent<NavMeshAgent>();
agent.SetDestination(targetPosition);The agent automatically computes the optimal route, steering cleanly around obstacles.
Practice NavMesh destination assignment test
Define a Start method. Inside, declare string hedefAdi = "HedefNoktasi"; and print "Hedefe yonelindi: " + hedefAdi to the console.
Starter code
using UnityEngine;
public class NavDestinationTester : MonoBehaviour
{
// Start icinde hedefAdi tanimla ve yazdir
}Sample solution
using UnityEngine;
public class NavDestinationTester : MonoBehaviour
{
void Start()
{
string hedefAdi = "HedefNoktasi";
Debug.Log("Hedefe yonelindi: " + hedefAdi);
}
}Expected output
Hedefe yonelindi: HedefNoktasi
Practice Agent stopping distance check
Define a Start method. Inside, declare float durmaMesafesi = 1.5f; and print "Durma mesafesi: " + durmaMesafesi to the console.
Starter code
using UnityEngine;
public class NavStoppingTester : MonoBehaviour
{
// Start icinde durmaMesafesi tanimla ve yazdir
}Sample solution
using UnityEngine;
public class NavStoppingTester : MonoBehaviour
{
void Start()
{
float durmaMesafesi = 1.5f;
Debug.Log("Durma mesafesi: " + durmaMesafesi);
}
}Expected output
Durma mesafesi: 1.5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method must be called to direct a NavMeshAgent toward an objective?
- agent.JumpToNav()
- agent.BakePath()
- agent.RunImmediately()
- agent.SetDestination() Correct answer
Explanation: In NavMeshAgent, the method that resolves the path and begins locomotion is SetDestination.
2 Include navigation namespace
using UnityEngine.____; public class EnemyAI : MonoBehaviour { }
using UnityEngine.AI; public class EnemyAI : MonoBehaviour { }
Explanation: To access NavMeshAgent and NavMesh types, the 'UnityEngine.AI' namespace is imported.
3 NavMesh elements
| Term | Meaning |
|---|---|
NavMeshAgent |
NavMesh pathfinding movement component |
SetDestination |
Sets target coordinate and starts path |
remainingDistance |
Current remaining distance to target |
stoppingDistance |
Distance to stop before the target |