- Home /
The question is answered, right answer was accepted
How to get a certain child from a Canvas?
Hello Unity Community!
I am trying to dynamically modify a Text from the UI. My hierarchy is as follows: Canvas->Panel->CurrencyText.
I am trying to modify the content of CurrencyText with:
_currencyText = GameObject.Find("Canvas").GetComponentInChildren<Text>();
_currencyText.text = string.Format("{0:0,0.00}", _currency);
However, these lines will only get the first Text type child from Panel. I will need to modify multiple Text type children.
So, how can I possibly access a certain child instead of just the first in the hierarchy?
Answer by Aevitas · Mar 03, 2015 at 10:37 PM
You could link it by adding a variable, either public, or [Serializable] private/protected
You could find all components with GetComponentsInChildren(), this will return an array of all Text components in all children AND itself (although the function name would state otherwise). You could then iterate on this array to find the correct one, either by name, tag, values, other components...
You could look it up by its hierarchy path name: gameObject.Find("Name/Childname/Childname").GetComponent();
Thank you very much. I'm at work right now and I can't try out any of the solutions. However, this seems to clear up all my problems. Thanks!