Pathfinding helps characters or objects find the best way to move from one place to another. It makes games feel smart and alive.
0
0
Pathfinding basics in Unity
Introduction
When you want a game character to move around obstacles to reach a target.
When you need enemies to chase the player without walking through walls.
When creating navigation for NPCs in a game world.
When you want to automate movement in a maze or complex map.
When designing AI that needs to find shortest or safest routes.
Syntax
Unity
using UnityEngine; using UnityEngine.AI; public class SimplePathfinding : MonoBehaviour { public Transform target; private NavMeshAgent agent; void Start() { agent = GetComponent<NavMeshAgent>(); } void Update() { if (target != null) { agent.SetDestination(target.position); } } }
NavMeshAgent is a Unity component that moves an object along a path.
SetDestination tells the agent where to go.
Examples
This sets the agent's goal to the target's current position.
Unity
agent.SetDestination(target.position);
Check if the agent has reached close to the destination.
Unity
if (agent.pathPending == false && agent.remainingDistance < 0.5f) { // Reached destination }
Change how fast the agent moves.
Unity
agent.speed = 3.5f;Sample Program
This script makes an object follow the player smoothly using Unity's NavMeshAgent. Attach it to an enemy or NPC with a NavMeshAgent component. Assign the player Transform in the inspector.
Unity
using UnityEngine; using UnityEngine.AI; public class FollowPlayer : MonoBehaviour { public Transform player; private NavMeshAgent agent; void Start() { agent = GetComponent<NavMeshAgent>(); } void Update() { if (player != null) { agent.SetDestination(player.position); } } }
OutputSuccess
Important Notes
Make sure your scene has a baked NavMesh for the agent to navigate.
NavMeshAgent automatically avoids obstacles and finds paths.
You can adjust agent settings like speed, acceleration, and stopping distance in the inspector.
Summary
Pathfinding helps game objects move smartly around obstacles.
Unity’s NavMeshAgent makes pathfinding easy to use.
SetDestination tells the agent where to go, and it handles the path automatically.