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

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

42454-2015-03-13-09-45-31-unity-3-pilotageunity-03-11-re.png

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>();
b.onClick.AddListener(()=>{
  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);
  objT.SetParent(aPanel);
  Button b = objT.GetComponent<Button>();
  objT.GetComponentInChildren<Text>().text = answer.GetQuestion(atype);
  b.onClick.AddListener(()=>{
    // Do something when the button is clicked/pressed
    DoStuff(answer);				
  });
}