To start off, I’m talking about caching references to other GameObjects on Start/Awake (whether it be children of the current obj, or a completely different one).
I am really trying to make my code re-usable across projects, and anytime I have to resort to comparing/looking for a GameObject by string I get a sick feeling in my belly!
I try to NEVER use Find(), ever. I try to use FindWithTag() sparingly (can’t have a different tag for every object…). I try not to use drag drop in the inspector, other then when I’m doing quick prototyping. So the next best thing I thought of using is:
// Example, caching references to specific children
private GameObject ref01, ref02, ref03;
foreach( GameObject go in GetComponentsInChildren<GameObject>() )
{
if( go.name == "myReference01" ) ref01 = go;
else if( go.name == "myReference02" ) ref02 = go;
else if( go.name == "myReference03" ) ref03 = go;
}
// I find the above better then (especially when looking for children):
ref01 = GameObject.Find("myReference01");
ref02 = GameObject.Find("myReference02");
ref03 = GameObject.Find("myReference03");
But I still don’t like it. I don’t like using strings.
Now, for a lot of my classes, I use self-reference assignment, which I do like, a lot. But I can’t have a different class for each GameObject I need a reference to! When the object in question has a script already attached this isn’t a problem, but what if it doesn’t? What if I only need a reference to it in order to access its GUITexture or GUIText, which are the only components attached to the GameObject in question?
In those situations, I can’t think of any way other then the ones I mentioned above (drag drop, string compare, ect…).
I’m really curious to find out if you guys have a better solution for these cases?! If you wouldn’t mind sharing your workarounds, tips tricks, please do, you’ll make me that much closer to choosing a solution to use everytime I come across this problem ![]()
Thanks for your time!
Stephane