- Home /
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.
I'm really not great at for loops but I think the reason your y and z prefabs aren't being instantiated at the right position is because you are saying i*2+1 and since i is 0 the first time (I think) you are practically saying 0*2+1 which will equal 1. Since you want it to appear at 0 and not 1 you might have to remove the +1. This might get you started =)
Answer by AtomicHippo · Dec 31, 2011 at 03:44 PM
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!
Answer by Bytebait · Dec 31, 2011 at 06:06 PM
A great reminder of how far I have to go in my programming. Thanks AtomicHippo!
Also, Love the yield WaitForEndOfFrame function!
Your answer

Follow this Question
Related Questions
Checking if object intersects? 1 Answer
[C#] How do I instantiate multiple objects at the same time? 1 Answer
A way to destroy these blocks faster? 1 Answer
Assign Names Problem 1 Answer
Instantiate only one Prefab per 40 unit 2 Answers