How to change the text of a Button with C# in 4.6

I’ve searched everywhere for this and I can’t find an answer. I am instantiating a set of 17 different buttons, and I want to be able to edit the text field of those buttons using C# code.

for(int i = 1; i<7;i++)
		{
			for(int k=1; k<4; k++)
			{
				GameObject createdbutton = (GameObject)Instantiate(button);
				createdbutton.transform.parent = this.gameObject.transform;

This successfully creates the buttons, but how do I now change the text field of each button, what is the correct command?

I am quite new to Unity and C# so please be very clear, thanks!

The new controls in 4.6 are pretty cool, but they’re also kind of weirdly designed. The Text element of all uGUI buttons is actually a separate, child element of the button itself. Try the following code:

 createdButton.GetComponentsInChildren<Text>().text = "New Super Cool Button Text";

I think it must not be GetComponentsInChildren, but GetComponentInChildren. “s” makes the difference.

createdButton.GetComponentsInChildren().text = “New Super Cool Button Text”;

This doesn’t work. GetComponent() has no defintion for “text”.

I think the best way to handle this situation is instead to keep an array of your button objects. First create an empty array of the same type as your Button.

Then, in your loop when you create the buttons, you might want to just push the button onto the end of the array right after you create it.

then, later on, in your event handler, or in the update function you could iterate over your button objects and set the .text property on them to be whatever you want(assuming you want them all to be the same text, then this will work fine).

However, if you wanted each button to have it’s own text, then it could still be done. back when you pushed the item onto the array you could create some kind of unique identifier variable, perhaps the variable could be called realName. you could assign each button a realName and then later use the variable to identify it. @EsoEs