- Home /
C# Should I store array of GameObjects or the scripts attached to them?
I'm dynamically creating GameObjects and attaching my script MapTiles to each one. I don't anticipate having to access the GameObjects at all, but I do anticipate interacting with the scripts. Is it better to store references to the GameObjects or their scripts in an array?
I'm assuming it's better to put the GO's in the array, but I couldn't find anything on the subject via Google, so I'd love to hear specific reasons why or why not to do it this way.
If it's helpful, here's a code snippet:
private void BuildLevel() {
print("BuildLevel() starting...");
print("Columns: "+levelDataColumns+", Rows: "+levelDataRows);
int columns = levelDataColumns;
int rows = levelDataRows;
mapTileArray = new MapTile[columns, rows]; //assign size to array
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
GameObject go = new GameObject();
MapTile mapT = (MapTile) go.AddComponent(typeof(MapTile));
mapTileArray[i,j] = mapT;
Material mat = GetLevelDataMaterial(i,j);
mapT.InitializeMapTile(i*10,0,j*-10,mat);
}
}
}
Thanks!
Answer by vexe · Sep 15, 2013 at 06:24 AM
You answered yourself:
"I don't anticipate having to access the GameObjects at all, but I do anticipate interacting with the scripts"
But then:
"I'm assuming it's better to put the GO's in the array"
What is it that you think is 'better' to store the GOs?
Not saying that it's BAD to store the gameObjects, but why would you do that if you don't need to ever access the gameObject
and all you need is the script component? - it doesn't make sense.
In fact, if you stored the GOs, what happens later when you want to access your MapTile
script from all elements in the array? you would have iterate and for each member you do a GetComponent< MapTile >
... Why?
$$anonymous$$ainly I was worried it was a gotcha scenario where not storing references to GameObjects would result in unexpected behavior. Thanks for the quick response!
If you ever needed your GO for some reason, you can always, at any time get a reference to the gameObject of your $$anonymous$$apTile
component by just my$$anonymous$$apTile.gameObject
Your answer
Follow this Question
Related Questions
Need help with an array. - C# 3 Answers
How to copy part of an array 2 Answers
Multiple Cars not working 1 Answer
[C#] Sorting a List of Gameobjects Alphabetically 2 Answers
Save Gameobject in Array 1 Answer