[4.6 - UI] Change text on button click via script

Actually my buttons changes a UIText with the specified text in the On Click().


I’m wondering how to change this specified text directly via script?!

If you are calling this from another script it you could use the AddListener function:

Button b = objT.GetComponent<Button>();
  objT.GetComponentInChildren<Text>().text = textVar;

Where objT is a reference to the Transform that the button is on (RectTransform is OK also) and textVar is the variable that stores the text you want the button to show.

From this, you should be able to make a more specialized script if you just want to be able to drop a script onto each button and change the text one by one.

ProTip!: Any variables used by the onClick listener should be local variables declared (or re-declared) inside your for loop. If not, all of the buttons edited through the loop with have the same value; the last value processed by the for loop!

foreach(Question a in qList) {
  // Set variable to pass to listener
  Question answer = a;
  // Create new button from existing prefab
  objT = (Transform)MonoBehaviour.Instantiate(buttonPrefab);
  Button b = objT.GetComponent<Button>();
  objT.GetComponentInChildren<Text>().text = answer.GetQuestion(atype);
    // Do something when the button is clicked/pressed