Exiting the Game Using a UI Button?

I’m trying to create a UI button that, when clicked, exits the game executable. How would I go about doing so?

1: Create a normal script with a public function that exits the game (use one of the standard methods)
2: Attach that script to an active GameObject (either the button itself or the camera for example)
3: On the button, add a new event
4: Drag the object you attached the above script to as the events target
5: Select the method in the drop down

Job done.

If you need to figure out how to close the game from script, just google it, as there are several ways and it’s sometimes different for different platforms

Thank you for your help,
However, I am experiencing some further problems.
In the script, I wrote:

void Update () {

        if (GUI.Button (Rect (130,40,80,20))) {
            Application.Quit();
        }
    }
}

However, the console is returning the errors:

  • Assets/NewBehaviourScript.cs(20,25): error CS1501: No overload for method Button' takes 1’ arguments
  • Assets/NewBehaviourScript.cs(20,33): error CS0119: Expression denotes a type', where a variable’, value' or method group’ was expected

First, it seems you are using an older method to make your UI. This question is better suited for this forum: Extensions and OnGUI. The method @SimonDarksideJ provided uses the new UI system that was introduced in 4.6. To your question, here are some corrections with comments to help you out:

// All functionality of the GUI class must be in the OnGUI() method
void OnGUI()
{
    // Make sure that you use "new" before Rect so that a new
    // Rect is created.  In C# this is necessary, but in UnityScript it is not.
    //
    // Make sure you are giving content to the button.  This can be
   // a string or texture, even if it is empty.
    if(GUI.Button(new Rect(130.40,80,20), "Quit") {
        Application.Quit();
    }
}
1 Like

Quick hands there @TrickyHandz beat me to that response. Curious as that case is very clearly detailed in the Unity docs (one of the few that is at the moment).

1 Like