- Home /
Can't get proper reference to nested (UI)Text object.
Hello,
There's a prefab that contains nested objects. I iterate through all the siblings (in c#) and it finds the (UI) Text object instance, but saving the reference is the problem for me. this is the piece of code I am using:
private GameObject hTextCarbon;
void Start () {
Transform[] allChildren = GetComponentsInChildren<Transform> ();
foreach (Transform t in allChildren) {
if (t.name == "txtCarbon")
hTextCarbon = t.gameObject;
}
hTextCarbon.text = "xxx"; // **ERROR: there is no such variable called 'text' in GameObject
}
If I change it to:
private Text hTextCarbon;
void Start () {
Transform[] allChildren = GetComponentsInChildren<Transform> ();
foreach (Transform t in allChildren) {
if (t.name == "txtCarbon")
hTextCarbon = t.gameObject ; // **ERROR:Cant Convert from GameObject to UnityEngine.UI.Text
}
hTextCarbon.text = "xxx";
}
Any Idea? Thanks in advance.
Answer by corn · Dec 31, 2015 at 10:51 AM
The problem is exactly as the error messages say. In your first code sample, you actually assign to hTextCarbon the GameObject holding the Text you're looking for. Then you try to modify hTextCarbon's text, but it doesn't have one ! It is a GameObject, not a Text. So this first method is 100% wrong.
The second method is better, but still no good : you try to assign a GameObject to a Text variable on line 7. hTextCarbon is a Text, t.gameObject is a GameObject. So what you need to do is assign to hTextCarbon the Text that t holds, not t's gameObject, with a simple GetComponent call.
private Text hTextCarbon;
void Start () {
Transform[] allChildren = GetComponentsInChildren<Transform> ();
foreach (Transform t in allChildren)
{
if (t.name == "txtCarbon")
{
// Get t's Text component
hTextCarbon = t.GetComponent<Text>();
}
}
if (hTextCarbon != null)
{
hTextCarbon.text = "xxx";
}
}
Great! It works now. Thanks for taking time and explaining the details.
Use comments and not answers when you don't have an answer!!! Converted to comment.