- Home /
GetComponent for gameobject list alternative
My current setup is that I have 2000+ empty gameobjects in a scene all called "Hex" with a tag "Hex" and with a script attached called "Hex" that stores all the relative information about each hex.
like:
movementCost
adjacentHexs
connectedHexs "for linked non-adjacent hexs"
weightValue[] "for each player"
ect.. ect..
the problem is that I am using code like this alot, over and over again to do different things like move players, enemies or alter the map:
foreach (GameObject hex in GameObject.FindGameObjectsWithTag("Hex"))
{
int Weight = hex.GetComponent<Hex>().weight;
//do something
int movementCost = hex.GetComponent<Hex>().movementCost;
//do something
GameObject[] adjacentHexs = hex.GetComponent<Hex>().adjacentHexs;
//do something
foreach (GameObject adjacentHex in adjacentHexs)
{
int adjacentWeight = adjacentHex.GetComponent<Hex>().weight;
//do something
int adjacentMovementCost = adjacentHex.GetComponent<Hex>().movementCost;
}
//do something
}
I am using the GetComponent over and over again all over my code and its getting ridiculous. I need a better way of working that will aloow me to store all the data I need about all the Hexs in one place so that I can access it without the repeated GetComponent.
I was looking into creating a Hex class and then creating a list but Im not sure how to implement it or how to make it work without the GetComponent slowing everything down.
Any ideas?
Answer by Hoeloe · Nov 09, 2013 at 11:17 PM
Keep a static list of Hex objects in your class. In the Start method in your hex class, add it to this list. When you destroy a Hex object, remove it from that list. You now have a list of Hex objects that do not need GetComponent calls.
As another point, to get rid of multiple calls to GetComponent, just create a temporary variable, like this:
Hex h = hex.GetComponent<Hex>();
And use that instead of calling GetComponent every time. That's not your only problem, though, as FindGameObjectsWithTag can be a pretty expensive operation too, so you don't want to be doing it every frame. Better to store the list somewhere and update it manually when it needs to change, rather than recreating it every frame.
Thank you, a "static list" is what I needed.
I should be able to remove the 2000+ instances of the Hex script from all the empties and get rid of all the GetComponent 's now :D
Here is the game that I am working on, as you can see its slow as hell atm and needs alot of recoding: https://dl.dropboxusercontent.com/u/38908748/$$anonymous$$ill_Dragons_for_Science/GamePlay_Prototype_V0.02/GamePlay_Prototype_v0.02.html