1
\$\begingroup\$

My Slider GameObject has a GUIText child. I am writing a C# script that should change the text component in the GUIText, but instead of this I am getting:

error CS1061: Type UnityEngine.GUIText[]' does not contain a definition fortext' and no extension method text' of typeUnityEngine.GUIText[]' could be found (are you missing a using directive or an assembly reference?)

 public Slider timeSlider; int i = 5; timeSlider.GetComponentsInChildren<GUIText>().text = 'Some Text' + i; //timeSlider.transform.GetComponentsInChildren<GUIText>().text = 'Some Text' + i; // doesn't work either 

From the documentation I understand that GUIText should have a 'text' variable - Would anyone know why ().text is invalid?

Thank you!

How the hierachy is:

enter image description here

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

You are using GetComponentsInChildren, which as the error message tells you, returns an array of Unity.GUIText objects. That array doesn't have a text property. So you will probably want to iterate over the objects returned or use a different method for accessing the component(s).

\$\endgroup\$
1
  • \$\begingroup\$ Good point. I just tried with timeSlider.GetComponentInChildren<GUIText>().text= "Some Text"; and get a NullReferenceException... would you have a suggestion for accessing the GUIText component (exact hierarchy in question)? \$\endgroup\$ Commented Jul 25, 2016 at 15:46
0
\$\begingroup\$

Script needs to run on the parent. Then use this:

 transform.FindChild("child name").GetComponent<GUIText>().text = "some Text"; 

Now why would you use GUIText and not just Text that is part of the new UI system is beyond me.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.