Dennis Hackethal’s Blog
My blog about philosophy, coding, and anything else that interests me.
Pathfinding in Unity
Disclaimer: I’m a mere beginner at Unity and game development generally. I wrote this for myself as I am learning and figured others might find it useful as well. Exercise caution when running this code!
Unity makes pathfinding shockingly easy. Building on this tutorial and using Unity version 2020.3.2f1, here's how I applied pathfinding to the specific scenario of getting an object to follow the player around:
- Create a terrain. Additionally, create two 3D objects: one for the player, one for the 'follower'. I made my player a capsule and my follower a cube, but you can make yours whatever you like. Position both objects on the terrain
- Optionally set up some obstacles like walls
- Implement character movement for your player object
- Download folder 'NavMeshComponents' and file 'NavMeshComponents.meta' from this repo and drag them into your project's Assets folder as per this post
- Back in the Unity editor, create an empty object in the hierarchy and call it 'NavMesh'. Add component 'NavMeshSurface', then click 'Bake'. This will identify walkable paths on the terrain, a prerequisite for pathfinding
- On the follower object, add component 'Nav Mesh Agent'. This step will enable you to have the follower object follow the player
Also on the follower object, add a script called ‘Follower’ with these contents:
using UnityEngine; using UnityEngine.AI; // <- important! public class Follower : MonoBehaviour { public NavMeshAgent agent; public PlayerController player; // Update is called once per frame void Update() { // Move follower object to player. This will find the shortest path // and go around obstacles. agent.SetDestination(player.transform.position); } }
Back in the Unity editor, drag follower's nav-mesh component onto follower script's public 'agent' property
Drag player onto follower script's public 'player' property
Optionally set follower's stopping distance (e.g. to 5). This will prevent the follower object from moving 'into' the player, in which case neither one can move anymore
That's it! As you move around your player, the follower object will follow wherever you go, navigating the terrain and going around obstacles.
As an extra challenge, consider how you could make the follower object follow the player only when the latter is close enough, or visible, or audible, or some combination thereof.
References
This post makes 1 reference to:
There is 1 reference to this post in:
- Comment #127 on post ‘Buggy Dogs’
What people are saying