Make a GameObject Follow a Path

Hello. I am trying to make a prefab follow a path. I have my prefab but Unity won’t let me assign the point positions in the inspector. It will only let me choose the positions when a prefab is in the hierarchy. How can I make this script work with my prefab? Thanks.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoisonPath : MonoBehaviour
{
    [SerializeField] Transform[] Points;
    [SerializeField] private float moveSpeed;
    private int pointsIndex;

    void Start()
    {
        transform.position = Points[pointsIndex].transform.position;
    }

   
    void Update()
    {
        if(pointsIndex <= Points.Length - 1)
        {
            transform.position = Vector2.MoveTowards(transform.position, Points[pointsIndex].transform.position, moveSpeed * Time.deltaTime);

            if(transform.position == Points[pointsIndex].transform.position)
            {
                pointsIndex += 1;
            }
        }
    }
}

When instantiating a prefab the newly created object is unable to remember any serialized variables assigned to it before instantiation. You will need to find the waypoints for the prefab after it is instantiated.

One way I was able to do this was to create an empty game object called waypoint container and give it its own tag. Put all of your waypoints into this container. You can then find that container by tag and get its children storing them into a list. Once you have that list you can convert it into an array and this will give you the points you need for your prefab to move across your game space.

private void FindMapWaypoints()
    {
        GameObject waypointContainer = GameObject.FindGameObjectWithTag("WaypointContainer");
        List<Transform> waypointList = new List<Transform>();
        foreach(Transform child in waypointContainer.transform)
        {
            waypointList.Add(child);
        }
        waypoints = waypointList.ToArray();
     
    }

I’m sure there are better ways to do this but this one has worked for me so far. I hope it works out for you!

Thanks for the reply. The console is saying “waypoints” doesn’t exist in the current context.

waypoints is the name for the Transform array in the code that I used. You would need to change that to the name of your Transform array or conversely change the name of your Transform array to waypoints.