Can I just clarify what is the best way to set text on a button through a script.
public GameObject myButton;
myButton.transform.Find("Text").GetComponent<UnityEngine.UI.Text>().text = "press me".
Surely that’s not the simplest way. I presume there are some button helper functions to set text on buttons? In Actionscript you would do myButton.text = “press me.” The idea of the new UI is that it’s nicer than the previous UI right? The above doesn’t strike me as simpler than
GUILayout.Button("press me")
Can’t you just store a reference to the Text object itself, and then use TextObject.text = “stuff”?
So I got to store a reference to the button AND the button of the text now?
That’s not an improvement from the last GUI. 
That’s what I’ve been doing, but if there’s a better way I’d also like to hear it!
It may look like it’s not an improvement but it really is, I had over 8 000 lines of OnGUI code running prior to 4.6.
For the past months I’ve been converting all of that to the new GUI, effectively setting hundreds of references like that. Guess what? I gained 40 FPS just like that.
Surely when you create a button, it should automatically create a reference to the text object in your script without you having to do anything. That would have been the best solution. i.e. have a reference to the text object in the Text script in the preview panel. Then at least you could have written something like:
myButton.GetComponent<UnityEngine.UI.TextButton>().text = "press me".
which would have been slightly better. Unity seems to refuse to make things simple for us! Even if you create your own TextButton class and add the reference you have to manually drag the text object into that reference.
I suppose the other option is to put this in the start function:
void Start(){
textObject = myButton.transform.Find("Text").GetComponent<Unity.UI.Text>();
}
for use later when setting the text later. e.g. textObject.text = “press me”;
Yes… that would work. So you would have:
class TextButton:Unity.UI.Button{
private Unity.UI.Text textObject;
void Start(){
textObject = myButton.transform.Find("Text").GetComponent<Unity.UI.Text>();
}
void setText(string s){
textObject.text = s;
}
}
and then replace the Button script with the TextButton script. Maybe I should work for Unity.
3 Likes