using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementSpeedController : MonoBehaviour
{
public List<Transform> objectsToMove = new List<Transform>();
public List<Vector3> positions = new List<Vector3>();
public int amountOfPositions = 30;
public int minRandRange, maxRandRange;
public bool randomPositions = false;
public bool generateNewPositions = false;
public float duration = 5f;
public bool pingPong = false;
private void Start()
{
if (generateNewPositions || (positions.Count == 0 && amountOfPositions > 0))
GeneratePositions();
StartCoroutine(MoveBetweenPositions(duration));
}
private void GeneratePositions()
{
for (int i = 0; i < amountOfPositions; i++)
{
if (randomPositions)
{
var randPosX = UnityEngine.Random.Range(minRandRange, maxRandRange);
var randPosY = UnityEngine.Random.Range(minRandRange, maxRandRange);
var randPosZ = UnityEngine.Random.Range(minRandRange, maxRandRange);
positions.Add(new Vector3(randPosX, randPosY, randPosZ));
}
else
{
positions.Add(new Vector3(i, i, i));
}
}
}
IEnumerator MoveBetweenPositions(float duration)
{
for (int i = 0; i < positions.Count; i++)
{
float time = 0;
Vector3 startPosition = objectsToMove[0].position;
while (time < duration)
{
objectsToMove[0].position = Vector3.Lerp(startPosition, positions[i], time / duration);
time += Time.deltaTime;
yield return null;
}
objectsToMove[0].position = positions[i];
}
}
}
Now only the first object in objectsToMove
is moving between the waypoints but I need all of the elements of objectsToMove
to move between the waypoints. If I try this:
objectsToMove[i].position = Vector3.Lerp(startPosition, positions[i], time / duration);
I will let out of bound index exception because the size of objectsToMove
is not the same the size of positions[i]
i
on objectsToMove because i belongs to the positions iteration. It's iterating the count of positions. If that is to work, you'll need to have the same count of objects as the positions array. Do you want all the objects to go through the same positions together or go to random positions from the positions list? \$\endgroup\$