- Home /
How to put spacing between Gameobjs in loop
m generating a (4X4)matrix of cubes in the start function and wish to put spacing between columns does anyone know the right way to do it
void Start () { for (int i=0; i
for(int j=0;j<GridHeight;j++)//column
{
spacing =new Vector3(2,0,0);
GameObject g=new GameObject ();
g.transform.position+=spacing;
g=Instantiate(gemPrefab, new Vector3(i ,j,0),Quaternion.identity)as
GameObject ;
g.transform.parent =gameObject.transform;
gems.Add(g.GetComponent<Gem>());
}
}
gameObject.transform.position = new Vector3(-2.5f,-2f,0f);
}
Answer by Polaris007 · May 16, 2014 at 01:11 AM
void Start ()
{
int temp;
for (int i=0; i<GridWidth; i++) //row
{
for(int j=0;j<GridHeight;j++)//column
{
g=Instantiate(gemPrefab, new Vector3 (i,j,0),Quaternion.identity)as GameObject ;
g.transform.parent =gameObject.transform;
temp=j;
g.transform.position+=new Vector3(i+1,temp+1,0); //THIS LINE
gems.Add(g.GetComponent<Gem>());
}
}
gameObject.transform.position = new Vector3(-2.5f,-2f,0f);
}
after tinkering a bit i found a way to do it..the commented line
Answer by Jeff-Kesselman · May 15, 2014 at 06:27 PM
I think you are over complicating this.
Try this{
void Start () {
Vector3 position = new Vector3(0,0,0);
for (int i=0; i<GridWidth; i++) //row {
for(int j=0;j<GridHeight;j++)//column
{
GameObject g = Instantiate(gemPrefab,position,Quaternion.Identity);
position.X += <xSpacing>;
}
position.Y += <ySpacing>;
}
}
xSpacing should be the xWidth of the object plus the empty space you want in between. ySpacing should be the yWidth of the object plus the empty space you want in between.
i found this a bit confusing but managed to find a solution g.transform.position+=new Vector3(i+1,temp+1,0); just had to put this
Answer by Oniony · May 15, 2014 at 06:28 PM
Why not make an int that adds every time the loop goes through? Example: on the first loop it is 0. The gets 2 added to it. So second loop it is 2 then gets 2 added to it. etc.
Your answer
![](https://koobas.hobune.stream/wayback/20220613145116im_/https://answers.unity.com/themes/thub/images/avi.jpg)