- Home /
Spawn many object
Hi all,
I need to fill a box with more sphere . For do this operation i want kno which can be the best solution? I have used Instantiate() in a for cycle, but when i do this all objects collide and go out of the box. i not need mandatory to do this at runtime but i don't know otheer way. Can anyone help me?
Thanks
so... you have a box you need to be full of spheres - what's stopping you to put it there in the editor if you don't need to do this at runtime? otherwise, if the collisions are your problem, you should experiment with the settings of mass and drag in your rigidbody or the material in your collider - don't take bouncy but rather something like wood or metal.
Thanks for reply Lee , i not use the editor because i must create 1000 sphere and this operation is long and boring. i will try to create it with another material like you have suggested. Thanks
yeah thousands of spheres would be quite annoying to place by hand ^^
Answer by aldonaletto · Nov 16, 2011 at 01:52 PM
To avoid this collision issue, you could instantiate the objects at the top of the box and let them fall. You could use a grid pattern to instantiate a row of spheres, yield, instantiate another row, yield again, and so on. NOTE: this loop should not be in Update, because it doesn't accept the yield instruction, but could be in Start - something like this pseudo code:
for (var q = 1000; q > 0; ){ for (var i = 0; i < 10; i++){ for (var j = 0; j < 10; j++){ pos = Vector3(i * sphereDiameter, someHeight, j * sphereDiameter); Instantiate(spherePrefab, pos + box.position, Quaternion.identity); q -= 1; // decrement counter } yield; // let Unity breath until next frame } }
A loop inside a loop and another loop in that loop 1..2..3 That is 3 loops! -.-
+1
Yes, it's a lot of loops - but I had no time to write a more elaborated thing, and wanted just to give the basic idea. The problem here is that only multiples of 100 spheres are instantiated - not a problem in this case, where 1000 spheres are needed.