# Code with Coroutine not working as intended.

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:

``````IEnumerator Start ()
{
for (int i = 0; i< numCubes ; i++)
{
for (int j = 0; j < numCubes; j++)
{
yield return StartCoroutine(CreateCube (i,j));
}
}
}
``````

This would work, however it creates a lot of overhead / garbage for each started coroutine. Such a simple thing would be better implemented like this:

``````IEnumerator Start ()
{
for (int i = 0; i< numCubes ; i++)
{
for (int j = 0; j < numCubes; j++)
{
CreateCube(i, j);
yield return new WaitForSeconds(1f);
}
}
}
void CreateCube (int i, int j)
{
GameObject box = GameObject.CreatePrimitive (PrimitiveType.Cube);
box.transform.position = new Vector3 (i * 2.0f, j * 2.0f, 0f);
}
``````

Here you only have one coroutine (the start method) and CreateCube is a normal method.