# Instantiate for loop problem

On an empty game object I have a script that is trying to instantiate a creation of a large block created from several smaller blocks.

I’m trying to instantiate a block of 10x10x10 of cubes 2m apart.

((This is only for my understanding of how to do this correctly. I could just make a prefab and call that once, but I’m curious as to how this could be solved.))

Here’s my bad attempt at solving this problem.

``````var prefab : Transform;
``````

for (var i : int = 0;i < 10; i++) {

Instantiate (prefab, Vector3(i * 2, 0, 0), Quaternion.identity);

Instantiate (prefab, Vector3(0, i * 2 + 1, 0), Quaternion.identity);

Instantiate (prefab, Vector3(0, 0, i * 2 + 1), Quaternion.identity);

}

This only makes a 10x10x10 along the x,y,z lines, however I can see right away that I’m messing up somehow as the first position of the y and z aren’t in the correct location.

It’s probably best to use 3 for loops here, one for each dimension.
Something like;

``````    var prefab : GameObject;
var offset : int = 2;//Distance between cube centers

function Start(){

for (var z = 0;z<10*offset;z+=offset){

for (var y = 0;y<10*offset;y+=offset){

for (var x = 0;x<10*offset;x+=offset){

Instantiate (prefab, Vector3(x,y,z), Quaternion.identity);

//Added this line so you can actually see how the cubes are being populated
yield WaitForEndOfFrame;

}
}
}
}
``````

This builds a row along x first, (for 10) then generates 10 of those rows along y(for 10x10), then duplicates the two of those along z (for 10x10x10).

Think that should work.
Happy new year!

A great reminder of how far I have to go in my programming. Thanks AtomicHippo!

Also, Love the yield WaitForEndOfFrame function!