- Home /
Can't add a GUI in C#??
OK I am a noob with GUIs in C# (mostly C# in general) and I'm trying to add an "about" page to my game. I have GUILayout.label for my button, but I can't add another one for the actual text for the about page. I want to get it to where I can show the text from a txt file (I know about text assets) and that's not the problem. The problem is that I can't add the new GUI that shows the information after I click the about button. Here's my code:
void OnGUI() { if (isLocked == false) { GUILayout.BeginArea (new Rect (0, 0, Screen.width, Screen.height)); GUILayout.BeginHorizontal (); GUILayout.FlexibleSpace (); GUILayout.BeginVertical (); GUILayout.FlexibleSpace (); GUI.skin = buttonSkinThing; if (GUILayout.Button ("About", "label")) { GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.EndVertical(); GUILayout.FlexibleSpace(); [Whatever GUIText here to show text from file/about page] Time.timeScale = 1; Debug.Log ("Resume Game"); } if (GUILayout.Button ("Exit", "label")) { Debug.Log ("Exit Game"); } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); GUILayout.FlexibleSpace (); GUILayout.EndVertical (); GUILayout.EndArea (); } else { Debug.Log ("CRAP"); } }
I know that some of it is junk like the flexible spaces and the endhorizontals, but all I need is for it to have a button that I can click that says "about". WHen I click that, I want it to go away and show another GUI with the text in a txt file. Anyone know why I'm messing this up?
Answer by Maui-M · Feb 04, 2014 at 10:36 PM
OnGui() is called constantly, so to change the GUIs displayed you will have to set up what is known as a state machine. This will allow you to display different GUIs based off of the current state of your application. Below is a simplified example of what you would probably want to implement.
enum CurrentState = State.MainMenu;
enum State {
MainMenu = 0,
About = 1,
Gameplay = 2
}
void OnGUI() {
if(CurrentState == State.MainMenu;) {
// All your other main menu GUIs
if (GUILayout.Button ("About", "label")) {
Debug.Log ("About State");
CurrentState = State.About;
}
}
else if(CurrentState == State.About){
// Show the about screen
if (GUILayout.Button ("Exit", "label")) {
Debug.Log ("Returning to menu");
CurrentState = State.MainMenu;
}
}
else if(CurrentState == State.Gameplay){
// Show ingame GUIs
}
}
A cleaner version would be to use a case statement instead of a bunch of if else statements.
enum CurrentState = State.MainMenu;
enum State {
MainMenu = 0,
About = 1,
Gameplay = 2
}
void OnGUI() {
switch(CurrentState)
{
case State.MainMenu:
MainMenuGUI();
break;
case State.About:
AboutGUI();
break;
default:
Debug.Log("NO CURRENT STATE");
break;
}
}
void MainMenuGUI() {
// Main menu GUI code here
}
void AboutGUI() {
// About menu GUI code here
}