Instantiate distance?

Hello. Suppose I have three cubes, that are all different lengths(height/width values are all the same), that I want to spawn in a row along the z axis. How can I make instantiate them so that there is no space between them(as soon as one cube ends, the next one spawns) ? Thanks

2 Answers

2

The cube's 'origin' is in the center of it. So you have to figure out how long the cube should be depending on the distance between it and the next cube based on the centers.

Let's say, for example, the cubes are 1, 2, 3 units in length respectively. If Cube 1 is centered at 0, we know it ends at .5. Since Cube 2 is 2 long, we know it must go from .5 to 2.5. Its center then is at (.5 + 2.5)/2 or 1.5. Cube 3 goes from 2.5 to 5.5, so its center is (2.5+5.5)/2 or 4.

I hope this helps

you should know the z size of the cube. let's say it's 3.

Vector3 pos = Vector3.zero;
for (int i = 0;i<numberOfCubes;i++)
{
Instantiate (cube,pos,Quaternion.identity);
pos.z+=3;
}

then you can set numberOfCubes to any number you want and cubes will start to apear in (0,0,0) (0,0,3). be careful, the offset (pivot) is in center of the cube so if you want to put cubes in a way that their edges should start from a special point you might require a addition. if you want to get the size from your collider it's easy too.

I would do this but use the Renderer.bounds property to get the dimensions. this way if you wanted to use cubes from a 3d package, you can. For example cubes from a 3d package can have any uv configuration you'd like.

This also assumes all cubes have the same length on z