- Home /
So, if transform.FindChild is the dumb way, what's the smart one?
I'm mucking around with a simple collectible card game prototype to push my skills with class architecture and code design, and while all is good so far, my curiosity is piqued. I've found threads over and over that state that traversing parent<->child hierarchies in code is a huge no-no for fast and re-usable code.
In my current case, I have a general card prefab that is a quad with two TextMesh children: CardTitle and CardText. The card prefab has a C# script with a method called AssignCard() that I call whenever I instantiate a new card prefab to tell the new prefab which card it is.
In AssignCard() I currently have the lines:
transform.FindChild("CardTitle").gameObject.GetComponent<TextMesh>().text = _name;
transform.FindChild("CardText").gameObject.GetComponent<TextMesh>().text = _text;
And they work. But I know there's a better way.
So, if you were in my shoes, how would you re-design this setup to get away from transform.FindChild and onward towards smart, beautiful code?
Caching the result of Find in your start function and accessing it whenever needed so you don't have to perform a Find every now and then.
Answer by MakeCodeNow · Jul 04, 2014 at 06:25 AM
The best way is always to store a reference to the objects in question, either exposed as properties in the editor or as private variables that you assign to once at runtime. As always, the fastest way to do something is to not do it at all!
Answer by JPoenisch · Dec 04, 2019 at 08:43 AM
In my opinion the best way would be to have the fields
[SerializeField] private TextMesh cardTitle;
[SerializeField] private TextMesh cardText;
assign both on your prefab via the Inspector (drag&drop) and later use them
cardTitle.text = _name;
cardText.text = _text;
Skips all expensive Find
and GetComponent
calls on runtime entirely. Both references are simply already serialized and stored in the prefab and thereby already assigned on every spawned instance of this prefab right away.
Your answer
Follow this Question
Related Questions
Block Placement Help 2 Answers
Cube Counter 1 Answer
Inspector Assigned Variables Not In Both Scenes 1 Answer
MonoDevelops on the fly code formatting off 1 Answer
unity error error CS1525: Unexpected symbol `(', expecting `identifier' 2 Answers