user4381598
user4381598

Reputation:

QuitApplication Button on unity

I am trying to create a Quit button in Unity, but when I add my script to the button and click it, it doesn't quit.

Here is my C# script:

    using UnityEngine;
using System.Collections;

public class Quit_App : MonoBehaviour {
    void OnClick() {
        Application.Quit();
    }
}

I have created it and assigned to the canvas using the UI, and I use the Button(Script) box in order to execute this code using the OnClick() box. There, I selected it as object MyButton and the Quit_App() function using a string name.

Upvotes: 1

Views: 14611

Answers (5)

maher salah
maher salah

Reputation: 11

if you mean exit Play Mode thats completely an other thing. because quit is only when its built into an app.

Quitting the app:

Application.Quit();

Quitting the play mode:

UnityEditor.EditorApplication.isPlaying = false;

Upvotes: 1

Marlon Assef
Marlon Assef

Reputation: 1541

First, this answer assumes that your code works and the only problem is that the Application.Quit () command does not execute.

The Application.Quit () command does not work when testing the application in the Unity Editor (for example, by pressing the "Play" button). It would close the Unity Editor.

To test, go to the "Files / Build and Run" menu.

This will build and execute the project and Application.Quit() will be execute properly.

Upvotes: 2

Pino De Francesco
Pino De Francesco

Reputation: 756

Your script assumes that calling the method OnClick will magically make the click detected, but that is not the case.

You need a Menu Manager script added to the scene exposing a public method to be binded to the Button component.

Here the setup you need: Button setup

The script MenuManager is attached to the MenuManager game object: Menu Manager Setup

The code in the MenuManager script is real simple:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MenuManager : MonoBehaviour {

    public void ExitNow()
    {
        Application.Quit();
    }

}

I uploaded the package with a fully functional implementation here.

Upvotes: 2

user4381598
user4381598

Reputation:

I find a semi-solution for this problem.I used this script that allows me to exit when i press the escape button.

    using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

    // Use this for initialization
    void Start () {
        if (Input.GetKey("escape"))
            Application.Quit();
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey("escape"))
            Application.Quit();
    }
}

Upvotes: 0

ahmedsafan86
ahmedsafan86

Reputation: 1794

After a search I found that onclick not a member of MonoBehaviour look at OnMouseDown on the following link http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html

Upvotes: 0

Related Questions