How do you actually change the text of a button?

I’m trying to automatically populate a list of buttons from a file. Everything works, until I try to edit the default text of the Instantiated button.
I’m trying this:

currentButton.GetComponentsInChildren<Text>().text = title;
I get an error saying that Text[ ] does not have a definition for .text, and so returns null. I’m not sure what is wrong here, but if anyone could point me in the right direction as I’m a bit new to unity.
Thanks

You are getting multiple components if you are using GetComponentsInChildren

GetComponentsInChildren = Text[ ] (array of Text Objects)

For arrays or List you can loop through using a for loop or a foreach
for loop:

var arr = currentButton.GetComponentsInChildren<Text>;
for (int i = 0; i < arr.Length; i++)
{
arr[i].text = title;
}

foreach loop:

foreach (var obj in arr)
{
   obj.text = title;
}

GetComponentInChildren = single Text object
For single objects, you can use their field/prop/methods, so you can now do obj.Text = title;

1 Like