Move an object along a path in Unity

Unlike Godot path follow Unity does not have a path follow component to easily implement this. We need to come up with our own algorithm to implement this. The best way to do this is using Unity’s navmesh and waypoint system.

If you have zero idea about what a navmesh is you can check out our post on how to implement AI navigation in Unity.

Let’s get started.

Scene setup

  1. Add the object you want to move in a path.
  2. Add a plane on which the object will move.
  3. Add a Nav Mesh Agent component to your object.

Setting up the Nav Mesh

  1. Select the plane.
  2. Go to the navigation window.
  3. Go to the objects tab.
  4. Check Navigation static.
  5. Go to the bake tab and enter the details of your object.
  6. Click bake. You should see a blue area on your plane. This is the movable area on your plane.
Nav mesh display in the scene view

Setting up our path and moving the object

  1. Create empty objects for every point in the path.
  2. Set the point in the location of the path.
  3. Create and add a new script to your object.
  4. Copy and paste the code below.
  5. Set your points to the position array variable in the script.
  6. Play the game and your object should follow the path
using UnityEngine;
using UnityEngine.AI;

public class Movement : MonoBehaviour
{
    public GameObject[] position;
    NavMeshAgent navage;
    int pos_value;
    
    // Start is called before the first frame update
    void Start()
    {
        navage=GetComponent<NavMeshAgent>();
        pos_value=0;
        
    }

    // Update is called once per frame
    void Update()
    {
        if(navage.remainingDistance<0.2f)
        {
            pos_value+=1;
            if(pos_value>position.Length-1)
            {
                pos_value=0;
            }
            navage.SetDestination(position[pos_value].transform.position);
            
        }
        
    }
}
Gif showing Object moving in path

You can do the same thing using Unity Lerp also. You can rotate through the positions when the lerp completes.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading