Changing GUI.Label text

I’m new to GUI stuff so please bear with me if this is very simple. I’ve been through the documentation and the forums but I can’t figure out how to do this.

I have a bunch of GUI.Buttons and a GUI.Label. I want to change the GUI.Label text depending on what button is pressed.

How do I do this?

I’m also curious how you access GUI stuff from external scripts. It seems like these two issues are related.

1 Like

you need to set the text content of a GUL.Label to a variable and then change that variable from an external script.

e.g.

public var labelText : String = "This is some text";

function OnGUI() {
    GUI.Label(Rect(10, 10, 140, 20), labelText);
}

then you just need to set the labelText variable from any where else in your code, such as by clicking a button.

e.g.

function onGUI() {
    if (GUI.Button(Rect(10, 40, 140, 20), "Change label")) {
        labelText = "Different text";
    }
}

Thanks.

That worked great. Unfortunately it only seems to work from within the same script. Is there a way to change the value from another scrip?

no worries.

yeah you can do that one of two ways. either get the value you want from another GameObject when you make the OnGUI call.

e.g.

function OnGUI() {
    var myObject : GameObject = GameObject.Find("anyGameObject");
    var labelText : String = myObject.GetComponent(anyComponent).myVariable; 
    GUI.Label(Rect(10, 10, 140, 20), labelText); 
}

or alter the variable in the component containing the OnGUI call externally.

e.g.

in the gui component (let’s say this is a script called GUIManager in a GameObject called myGUIObject):

public var labelText : String = "This is some text"; 

function OnGUI() { 
    GUI.Label(Rect(10, 10, 140, 20), labelText); 
}

and in any external script:

public function changeLabelText() : void {
    var myObject : GameObject = GameObject.Find("myGUIObject");
    myObject.GetComponent(GUIManager).labelText = "Different text";
}

That did the trick. Thanks for your help.