The waypoints script :
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Waypoints : MonoBehaviour
{
public Transform objectToMovePrefab;
public int numberOfObjectsToMove = 1;
//with this approach, you use GameObjects to represent your waypoints
//(they can be empty if you want the waypoint to be invisible)
[SerializeField] private List<Transform> waypoints;
private void Start()
{
for (int i = 0; i < numberOfObjectsToMove; i++)
{
var parent = GameObject.Find("Moving Object Parent");
var objectToMove = Instantiate(objectToMovePrefab, parent.transform);
objectToMove.name = "Platfrom";
}
}
public int Count => waypoints.Count;
public Vector3 GetWaypoint(int index)
{
return waypoints[index].position;
}
}
Then in the editor I added this script to the prefab :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaypointsFollower : MonoBehaviour
{
[SerializeField] private Waypoints waypoints;
[SerializeField] private float speed = 5f;
[SerializeField] private bool goBack = false;
[SerializeField] private float delay;
private float startTime;
private int waypointIndex = 0;
private void Start()
{
startTime = Time.time + delay;
waypoints = GameObject.Find("Waypoints").GetComponent<Waypoints>();
}
void Update()
{
if (Time.time < startTime) return;
Vector3 waypoint = waypoints.GetWaypoint(waypointIndex);
//movement
float distance = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, waypoint, distance);
//check if we've reached the waypoint
float threshold = .1f; //how close is considered having reached the waypoint
if (Vector3.Distance(transform.position, waypoint) < threshold)
{
//wraps back to 0 when we reach last waypoint
if (goBack)
{
waypointIndex = (waypointIndex + 1) % waypoints.Count;
}
else
{
if (waypointIndex != waypoints.Count - 1)
waypointIndex = waypointIndex + 1;
}
}
}
}
The delay is working but it's delaying all the WaypointsFollower's so they move at the same time after the delay.
I want that even if all the Followers have the same delay value for example 3 so the first one will start moving after 3 seconds then the next follower will start moving after another 3 seconds and so on and not that they all delay for 3 seconds and move together but to make delay so there will be spaces between the followers when they are moving.