Finding all text field values under a parent object

Hi
I am trying to get the values from text fields in my scene, but not all of them.

I know how to get objects of type:

    var drinks = GameObject.FindObjectsOfType<Text>();

but this gets every text field in my scene.

So I then tried to tag them all, and just get those items:

   var drinks = GameObject.FindGameObjectsWithTag("drinktag");

But then i can’t work out how to get the information held within each of the text fields as this doesn’t work

  foreach (GameObject drinkis in drinks)
        {
            string drinkValue = drinkis.Text;

i have also tried

  foreach (var drinkis in drinks)
        {
            var drinkValue = drinkis.Text;
           var nameofdrink = drinkis.name

I can get the name of the object but not the value

I really need the value and I am going round in circles trying to find it
I have tried to search for a solution but no luck so hoping someone here can help me :slight_smile:
thanks

that should help you: Unity - Scripting API: Transform.GetChild

you will have to loop through all the children and try to get its component, if so, do whatever with if, otherwise keep looping through

thank you
I looked at that but didn’t understand it or how it relates! I can now loop through all the gameobjects and get their names, using FindGameObjectsWithTag()

I just can’t get the value written to the text field. Any ideas?
thanks

If its a child, why would you search it by tag not by what i just posted?

If you have found your Text by any way you are doing it,
here is a link to the Text Component https://docs.unity3d.com/2018.3/Documentation/ScriptReference/UI.Text.html

there are all the functions “Text” provides

There’s actually a method called GetComponentsInChildren() which does precisely what you want.

A Text field has a property “text” (lowercase T) which contains the text entered into the field.

2 Likes

@Ray_Sovranti thank you so much - that is exactly what I needed

Clear, helpful and the solution!
Anyone else stumbling over this post… my solution:

 public GameObject drinkstats;
 
var drinks = drinkstats.GetComponentsInChildren<Text>();
foreach (var drinkis in drinks)
        {
            var nameofdrink = drinkis.name;
           var drinkValue = drinkis.text;
            Debug.Log("name of drink: " + nameofdrink);
            Debug.Log("drinkValue: " + drinkValue);
}

Yes, I was confused by this too…there’s the Component “text”, which has the property “text” (among others) in it.

You can also do this:

foreach (var drinkis in drinks)
        {
            var nameofdrink = drinkis.GetComponent<Text>().text;
            Debug.Log("name of drink: " + nameofdrink);
}
1 Like

That’s entirely unnecessary/redundant. “drinkis” is already referring to the Text object.

Correct, I misread.