- Home /
Issue with instantiating multiple clone GameObjects
Hi, I'm trying to create a 50x50 2d Array of tiles, it works perfectly however in the Hierarchy after I run the code, I get a bunch of "New Game Object" GameObjects with no properties.
Could you tell me why and eventually how to fix it? Everything else in the code works fine and gets me the desired results.
Thank you.
public class Matrice : MonoBehaviour
{
public GameObject referenceTile;
GameObject[,] griglia = new GameObject[50, 50];
Vector2 grigliaPos;
// Start is called before the first frame update
void Start()
{
generaGriglia();
}
void generaGriglia()
{
for (int i = 0; i < 50; i++)
{
for (int j = 0; j < 50; j++)
{
GameObject gridSpace = new GameObject();
gridSpace = referenceTile;
float posX = i -24.5f;
float posY = j -24.5f;
gridSpace.name = "X: " + posX + " " + "Y: " + posY;
gridSpace.gameObject.tag = "MapTiles";
griglia[i, j] = (GameObject)Instantiate(gridSpace, new Vector3(posX, posY, 0), Quaternion.identity);
}
}
}
}
Answer by Casiell · Mar 19, 2020 at 10:49 AM
GameObject gridSpace = new GameObject();
So here you are creating new, empty gameobject (not sure why). This is the New Game Object in your hierarchy
gridSpace = referenceTile
Here you override the reference to that object with your prefab reference
gridSpace.name = "X: " + posX + " " + "Y: " + posY;
gridSpace.gameObject.tag = "MapTiles";
Here you modify that prefabs (not prefab instance, prefab itself) properties. You really shouldn't do that like ever.
griglia[i, j] = (GameObject)Instantiate(gridSpace, new Vector3(posX, posY, 0), Quaternion.identity);
Here you finally instantiate the prefab.
So here is how this part of the code should look like:
GameObject gridSpace = (GameObject)Instantiate(referenceTile, new Vector3(posX, posY, 0), Quaternion.identity); //instantiate prefab. creating new GameObject is absolutely unnecessary
float posX = i -24.5f;
float posY = j -24.5f;
gridSpace.name = "X: " + posX + " " + "Y: " + posY; //modify INSTANCE properties, not the prefab itself
gridSpace.gameObject.tag = "MapTiles";
griglia[i, j] = gridSpace; //add the object to your array
Had to put
GameObject gridSpace = (GameObject)Instantiate(referenceTile, new Vector3(posX, posY, 0), Quaternion.identity); //instantiate prefab. creating new GameObject is absolutely unnecessary
below
float posX = i -24.5f;
float posY = j -24.5f
due to undeclared variable error, however everything else worked perfectly.
Thank you very much, you solved my problem.
Your answer
Follow this Question
Related Questions
2D Array of GameObjects... 1 Answer
Problem with object generation script? 1 Answer
2D Array's 1 Answer
Multiple Fire Points 2 Answers
How to remove null's from 2d array ? It's removing but only 2 out of 4 null's. 0 Answers