- Home /
 
Adding a Gameobject to an array makes all elements of that array equal to the object
I'm trying to make a 2d array, then start a loop where i create a tile and store that tile into my array, then start a new loop for debugging purposes which takes a tile based on its position in the array and checks in has the correct information (x and y position). however, upon debugging, it appears that all the tiles in that array now have the same x and y position as the very last one.
Here is my code:
 public GameObject emptySpace;
 GameObject[,] board;
 public void makeBoard (int x, int y){
     board = new GameObject[x, y];
     for (int i = 0; i < x; i++) {
         for (int j = 0; j < y; j++) {
             GameObject s = emptySpace as GameObject;
             OccupiableSpace o = s.GetComponent<OccupiableSpace> ();
             o.xPos = i;
             o.yPos = j;
             Instantiate (s, new Vector2 (i, j), Quaternion.identity);
             int id = i * y + j;
             print ("x is " + i + " , y is " + j + " ,space number " + id + " has been created");
             board [i, j] = s;
         }
     }
     for (int i = 0; i < x; i++) {
         for (int j = 0; j < y; j++) {
             GameObject s = board [i, j];
             OccupiableSpace o = s.GetComponent<OccupiableSpace> ();
             int id = o.xPos * y + o.yPos;
             //if (o.xPos == i && o.yPos == j) {
             print ("x is " + o.xPos + " , y is " + o.yPos + " ,space number " + id + " has been located");
             //}
         }
     }
 }
 void Awake (){
     makeBoard (3, 4);
 }
 
               here is the console:


Answer by BastianUrbach · Apr 15, 2018 at 07:24 AM
In line 12 you clone s which creates a new GameObject but doesn't change the value of s. Instead, it returns the newly created object. Since you only ever use s afterwards, not the clone, you perform all operations on the same GameObject.
 Replace line 12 with 
s = Instantiate (s, new Vector2 (i, j), Quaternion.identity);
$$anonymous$$any thanks, i knew it was something dumb like that :)
Your answer
 
             Follow this Question
Related Questions
2D Array of GameObjects... 1 Answer
How to check if a specific gameobject is in the array? 1 Answer
selected object in array lost in translation 0 Answers
How to remove objects from a list ? 3 Answers
How do you save GameObject[]? 1 Answer