I would like the following code to create a cube every second but it operates otherwise:it waits a second and then creates all of them without waiting a second. How can i change this code to make it create a cube, wait a second, and then create another? Thanks for your time.
public int numCubes = 10;
// Use this for initialization
void Start () {
for (int i = 0; i< numCubes ; i++)
{
for (int j = 0; j < numCubes; j++)
{
StartCoroutine(CreateCube (i,j));
}
}
}
IEnumerator CreateCube (int i, int j)
{
GameObject box = GameObject.CreatePrimitive (PrimitiveType.Cube);
box.transform.position = new Vector3 (i * 2.0f, j * 2.0f, 0f);
yield return new WaitForSeconds(1f);
}
Your problem is that you start many coroutines at once that will spawn 1 cube each instead of starting one coroutine that will spawn many. This is the corrected version of your code:
public int numCubes = 10;
void Start()
{
StartCoroutine(CreateCube());
}
IEnumerator CreateCube()
{
for (int i = 0; i < numCubes; i++)
{
for (int j = 0; j < numCubes; j++)
{
GameObject box = GameObject.CreatePrimitive(PrimitiveType.Cube);
box.transform.position = new Vector3(i * 2.0f, j * 2.0f, 0f);
yield return new WaitForSeconds(1f);
}
}
}
Your Start method starts 100 coroutines at once. Those will all run “simultaneously” (not actually but from the a concept point of view). Waiting can only happen inside a coroutine. A coroutine runs independent from the code that started the coroutine unless you yield on that coroutine as well. However that is only possible when the starting code is also inside a coroutine.
So your Start method would need to be a coroutine as well: