# Grid from Vector3 Array

Howdy,

I’m trying to create a grid of Vector3 ‘spaces’ which are elements of an array. The grid should be four items per row. The aim is to place objects at in these spaces by their index in the array (so for example I could get the Vector3 at array index [4] and place a gameobject there.)

here’s what I’ve got:

``````PositionGrid = new Vector3[256];

for(i = 0; i < PositionGrid.length; i++)
{
for (var y = 0; y < 4; y++) {
for (var x = 0; x < 4; x++) {

PositionGrid[i] = Vector3((x +i ),(y+i),0);

}
}

}
``````

can some one point me in the right direction? Thanks!

``````PositionGrid = new Vector3[256];

for(i = 0; i < PositionGrid.length; i+=4)
{
for (j = 0; j< 4; j++) {

PositionGrid[i+j] = Vector3(i/4,j,0);

}

}
``````

I don’t know what your intention was, but you’re calculating and storing 16 different values (4*4) for each i, each overwriting the last. So for any given value of ‘i’, you calculate values for ‘y’ from 0 to 3 and for ‘x’ from 0 to 3, but only the last value calculated remains in PositionGrid after the inner loops complete. I suspect you need to re-think what you’re trying to do…
@ivkoni: might be closer to the intention, but still wont work; it’ll try to store 259 values into PositionGrid, resulting in an array index bounds error.

I doubt this would be the case

Really? What happens at i = PositionGrid.length-1, j = 3?

i will never = PositionGrid.length-1, since it is incremented by 4 ( i+=4). Last i would be 252.

Doh! Missed that…

Great ivkoni, works perfectly. Even better, I can see WHY it works, Thankyou!