I’m trying to store a grid that I have instantiated for a simple ‘board game’ prototype. I decided that I would like to store each square on the board in an array (I think it would work well as a part of the programming of the various game mechanics to be able to access squares just by knowing the x and y ‘grid’ coordinates).
The basic code that I started with was this:
var gridArray : GameObject[,];
gridArray = new GameObject[mapSize.x, mapSize.y];
for (j = 0; j < mapSize.y; j++){
for(i = 0; i <= mapSize.x; i++){
newSquare = Instantiate (squareTileUnexplored, Vector3.zero, Quaternion.identity);
newSquare.transform.localPosition = Vector3(i , 0, j);
gridArray[i, j] = newSquare;
print ("current grid position = " + gridArray[0,0].GetComponent(Transform).position);
}
}
However, the print command at the end is highlighting a problem. Whatever is stored in gridArray[0,0] is being changed every single time that something else is being added to the array in the For loop. The console shows a different transform.position for the GameObject being stored in gridArray[0,0] after every iteration of the loop (in fact it just prints the most recent newSquare position.
I’m sure this is a simple mistake, but I haven’t figured it out yet.
Yes, I know. I didn’t make it clear in my original post, but the output in the console changes every time, despite supposedly printing the ‘same’ thing. i.e. I’m actually seeing the transform.position of the last GameObject added to the array, regardless of where it was added (not [0,0] as far as I can tell).
This works just fine. gridArray[0,0] is the same all the way. And perfect 5 by 5 array is created in front of the camera.
public var mapSize_x : int = 5;
public var mapSize_y : int = 5;
public var squareTileUnexplored : GameObject;
function Start () {
var gridArray : GameObject[,];
var newSquare : GameObject;
var j : int = 0;
var i : int = 0;
gridArray = new GameObject[mapSize_x, mapSize_y];
for (j = 0; j < mapSize_y; j++){
for(i = 0; i < mapSize_x; i++){
newSquare = Instantiate (squareTileUnexplored, Vector3.zero, Quaternion.identity);
newSquare.transform.localPosition = Vector3(i , 0, j);
gridArray[i, j] = newSquare;
print ("current grid position = " + gridArray[0,0].GetComponent(Transform).position);
}
}
}
Thanks everyone. I managed to get it to work by taking Zaxvax’s code and taking it out of the start function for my purposes. The mapsize wasn’t zero, but the ‘j <= mapsize’ was a typo, I don’t quite know what else I had done wrong the first time round!