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…
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.
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?
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
}
}