Convert Buttons Text to String

Hello, I wish to convert the Button’s text to string. So far I have:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;

public class Button_CheckAnswer : MonoBehaviour {

public void CheckAnswerOnClick(object sender, EventArgs e){
Button clickedButton = (Button)sender;
string answerOption = (sender as Button).Text;
Debug.Log ("Selected answer "+answerOption);
}
}

But this gives the following error on this line “string answerOption = (sender as Button).Text;”:

Assets/Button_CheckAnswer.cs(14,58): error CS1061: Type UnityEngine.UI.Button' does not contain a definition for Text’ and no extension method Text' of type UnityEngine.UI.Button’ could be found (are you missing a using directive or an assembly reference?)

Thank you for any help

First always use code tags.

Second, the issue is buttons don’t have text. Text has text. If you have a button with text, you actually have a button with a text child. Which means you’ll need to get the child. Depending on your button, the default is the first child.

clickedButton.transform.GetChild(0).GetComponent().text is where the text would actually be.

I would recommend clickedButton.GetComponentInChildren().text actually. Easier to read, cleaner, more reliable (what if someone later adds another child to the button?).

Doesn’t GetComponentInChildren find the first instance of something? So if I added another Text child above the other, it would still possibly mess things up.

Even findChild has possible errors, as you could rename the child. Really, all three are prone to errors.

Another option is to add a custom script to the Button, add property to it of type Text and drag the child Text component to it. You can then get that component off the button and directly reference the Text child. This also resolves issues where you have multiple text children - just add additional properties to this component.

// add this to the object that has the Button component
class MyTextReferenceComponent : Monobehaviour
{
  public Text labelText;               // hook these up in the editor by 
  public Text otherLabelText;     // dragging the child label components to it
}

Then in your original code…

var textReference = GetComponent<MyTextReferenceComponent>();
textReference.labelText.text = "My new text";
1 Like

That’s a great example why this extremley useful and modular “open” component based design can sometimes be an overkill for such simple things, because everything can be messed up using the editor.

Best way would probably to encapsulate it in a subclass of Button.