- Home /
Change Text of GUI Button from Script
I am trying to make it so when the button is pressed it changes its own text. Heres what Ive been trying with no success.
var achButton = GUILayout.Button("Show Achievement List");
if (achButton)
{
achButton.text = "Hide Achievement List";
}
help is appreciated.
The BUtton method is called every frame, you can pass in any text you like. When the button is pressed the method returns true -- when this happens you should set a variable so you know to change the text.
im aware if that but I dont know how to input text.
Answer by Jean-Fabre · Jan 31, 2011 at 06:14 AM
Hi,
This is one way to do it:
Basically, you create a boolean variable AchievementVisible and this is what you toggle when the user actually click on the button, then you run a function that update both the text of the button and also show or hide the achievement gui. Notice that I store the button's label in a separate variable, my OnGUI function becomes clearer and not cluttered.
public var AchievementVisible:boolean = true; public var HideText:String = "Hide Achievement List"; public var ShowText:String = "Show Achievement List";
private var currentText:String;
function Start(){
UpdateAchievementVisibility();
}
function UpdateAchievementVisibility(){
if (AchievementVisible){
currentText = HideText;
}else{
currentText = ShowText;
}
}
function OnGUI(){
if (GUILayout.Button(currentText)){
AchievementVisible = ! AchievementVisible;
UpdateAchievementVisibility();
}
if (AchievementVisible){
GUI.BeginGroup (Rect (Screen.width / 2 - 50, Screen.height / 2 - 50, 100, 100));
GUI.Box (Rect (0,0,100,100), "Achievment");
GUI.EndGroup ();
}
}
Hopefully the rest is all self explanatory.
Bye,
Jean
Answer by T. · Jan 31, 2011 at 06:56 AM
Create a string and store what you want displayed in that, then update the contents of the string and the buttons text will update along with it.
Heres some psudeo code
var buttonText : String = "Show Trophies"; var buttonPressed : Boolean = false;
if Button if(!buttonPressed) buttonText = "Hide Trophies" else { buttonText = "Show Trophies" buttonPressed = True; }
Hope that helps! :)
it wasn't intended to be copy/pasted. only the logic for doing it.
it's much more helpful to have the code so we can understand how it works. the script objects, the format, etc. it's all needed for the logic to work.
Your answer
Follow this Question
Related Questions
Change text gui.button in a for bucle 1 Answer
GUI & GUI Text Disappear When Publishing 6 Answers
How do I set a GUI button's text using a string from another script? 0 Answers
Find GUI Button and Assign Text 1 Answer
How can I combine GUI button with script that is put on different gam objects? 1 Answer