# Attach movement to each list object

How would i move every sphere that gets spawned every 2 seconds ? Basically i want every sphere to follow the previous spawned sphere or even all N-1 spheres should follow the first spawned sphere along a predefined path and they should keep rolling as a train of spheres. I am lost when i try to imprint movement to each sphere.

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

public class Spawner : MonoBehaviour
{
public GameObject[] prefabs;
public List<GameObject> listBalls = new List<GameObject>();
private GameObject x;
public int timer = 0;
private float movementSpeed = 5f;

void Start()
{
createBall();
}

void Update()
{
if (Time.time - timer > 0.8f)
{
createBall();
timer += 2;
}
listBalls[listBalls.Count-1].transform.position += new Vector3(0, 0, movementSpeed * Time.deltaTime);
}

void createBall()
{
x = prefabs[Random.Range(0, prefabs.Length)];
Instantiate(x, x.transform.position, Quaternion.identity);
}

void moveBall(GameObject x, GameObject y)
{
x.transform.position += y.transform.position - new Vector3(0,0,-1);
}
}

void Update()
{
if (Time.time - timer > 0.8f)
{
createBall();
timer += 2;
}
foreach (GameObject item in listBalls)
{
item.transform.position += new Vector3(0, 0, movementSpeed * Time.deltaTime);
}
}

$$$$

• Are you familiar with using loops? – Kevin Jul 27 '20 at 22:06

There are several ways to do this, depending on how exactly you want the balls to move. Most solutions are going to use some kind of loop. If you aren't familiar with loops, you should read some tutorials on loops in C#.

Example 1: All balls move same direction/distance each frame

Vector3 movement = new Vector3(0, 0, movementSpeed * Time.deltaTime);

foreach (var ball in listBalls) {
ball.transform.position += movement;
}


Example 2: Each ball moves towards the next ball

float distance = movementSpeed * Time.deltaTime;
//move the last ball
listBalls[listBalls.Count - 1].transform.position += new Vector3(0, 0, distance);

//move each ball (except the last) towards the next ball
for (int i = 0; i < listBalls.Count - 1; i++) { //note we don't want to move the last ball again
Transform ball = listBalls[i].transform;
Transform nextBall = listBalls[i + 1].transform;
ball.position = Vector3.MoveTowards(ball.position, nextBall.position, distance);
}

• i litterally just did that, edit added, but the movement is staggered, i suspect the foreach loop shouldnt be added in the Update method? I am looking for a Zuma like movement of the balls. – mavish Jul 27 '20 at 22:26
• @mavish What do you mean by "the movement is stagged"? You'll need to run the loop regularly to update the positions of all of the balls; Update()` is generally a good starting place for that kind of thing. – Kevin Jul 27 '20 at 22:50