Move 10 GameObjects, one at a time

Hello all. After a long break (some years) I have decided to come back and try to create some stuff.

I’m a bit rusty in Unity, though. What I’m trying to achieve actually seems fairly simple.

I have an array of 10 GameObjects (Spheres), and I have a method called “Move” which will move a given sphere, wherever. I’m trying to move one sphere at a time, every 5.0 seconds.

GameObject[] spheres = new GameObject[10];
float timeBetweenLaunches = 5.0f;

for (int i = 0; i < 10; i++)
{
     StartCoroutine(Utils.Move(spheres[i], timeBetweenLaunches));
}

This code moves all 10 spheres at the same time.

I know why this code doesn’t work (the for-loop executes extremely fast, there is really no time between loops). However I can’t come up with a solution, even though I’m sure it’s pretty simple…

How can I solve this problem?

Thank you in advance! :slight_smile:

In your coroutine, start it with:
yield return new WaitForSeconds(5);
Then the code.

or do it after the code is complete.

or you can make the loop code a coroutine, and put the delay at the end of each loop. Is that c# or unity script? The coroutine code is a little different for unity script, I think.

Thank you for the answer. I’m already doing that:

(in Utils.cs):

public static IEnumerator Move(GameObject sphere, float time)
{
    yield return new WaitForSeconds(time);

    // Here goes code for translating sphere, not relevant
}

Initially, each Sphere is at rest. I just need to move them one at a time. Would you give me a bit more detail on how to implement your solution fire7side?

here is a sample of how to run a Coroutine

using UnityEngine;
using System.Collections;

public class ExampleCode : MonoBehaviour
{

    GameObject[] spheres = new GameObject[10];
    float timeBetweenLaunches = 5.0f;
   
    void Start()
    {
        StartCoroutine(Example());
    }

    IEnumerator Example()
    {
        for (int i = 0; i < spheres,Length; i++)
        {
             Move(spheres[i]); 
             yield return new WaitForSeconds(timeBetweenLaunches);
        }
    }
   
    void Move(GameObject sphere)
    {
      //code to move the shpere
    }
}

Thank you @johne5 ! I will try that out tomorrow and come back with updates.

Did you get it working?

I did Johne! I will paste a GIF as soon as I get home.

There we go, I attached the GIF to this reply.

In reality I was not using Spheres, but Fruits, in my chop-only-that-kind-of-fruit type of game :stuck_out_tongue: Your help was very helpful, thanks!

3272810--252956--insta.gif