- Home /
How to FindChild RectTransform and access its Text
Im trying to parse my hierarchy and find 3 different labels with a text component on each of them:
labelText = buttonObject.transform.FindChild("Firstname").GetComponent<Text>();
labelText.text = userContactsArray[0][i];
labelText = buttonObject.transform.FindChild("Lastname").GetComponent<Text>();
labelText.text = userContactsArray[1][i];
labelText = buttonObject.transform.FindChild("Description").GetComponent<Text>();
labelText.text = userContactsArray[2][i];
But I get error "NullReferenceException: Object reference not set to an instance of an object" as if it does not find the object at all.
Is there difference with RectTransform and transform or why exactly I can not find the object? I tried something like RecTransform.FindChild but without luck. Also in documentation it was saying like (RectTransform)transform.FindChild but it didnt work either.
Thanks in advance :)
Answer by Mmmpies · Dec 19, 2014 at 03:05 PM
Flying blind as I don't have access to Unity but null reference means it can't find a reference to the object. Where are you setting the buttonObject or userCOntactsArray?
also you can get the child object by number so
transform.GetChild(0).GetComponent<Text>();
or you could just set transform.
GetChild(0).GetComponent<Text>().Text = userContactsArray...
edit: Man am I ever gonna remember to code with
<Text>
in it in code to stop ot from vanishing!
I did the check so that the objects do exists with buttonObject and userContactsArray. But just when I try to use Find with a RectTransform it return null.
I will try to make repro file to show it.
I've now got better Internet access! If you look up the API for RectTransform here then there is no FindChild just RectTransform.Find for looking up the name as you do, or RectTransform.GetChild for looking up via the int index of the child.
Guess they changed the name for RectTransform, or, having just looked FindChild may be deprecated as it no longer appears in Transform either.
Hope that helps fix the issue for you.
Answer by tothemario · Dec 04, 2019 at 08:20 AM
RectTransform inherits from Transform. Navigating the hierarchy with transform.Find is the same.
I think transform.Find is working well, but GetComponent() is returning null because probably the component you are using in the game object is a , or maybe a