Application.Quit not working?!

Hello,
Weel I have this script:

function Quit() {
print("Unity, please Quit!!!");
Application.Quit();
}

But it is not working. I call the functioni from a UI button. It does prints the string, but it doesnt quit!

What is wrong???

You need to quit the game differently if it is being run in the editor. This does not close the Unity editor if you are running the game within Unity it only closes the game.

public void QuitGame()
{
    // save any game data here
    #if UNITY_EDITOR
        // Application.Quit() does not work in the editor so
        // UnityEditor.EditorApplication.isPlaying need to be set to false to end the game
        UnityEditor.EditorApplication.isPlaying = false;
    #else
        Application.Quit();
    #endif
}

Your game doesn’t close when testing it in the editor (pressing the play button) because it would close unity… and that means loosing everything, having to open it again, etc.

To test it you should build and run your game:

Fast way: Files>Build and Run

Slower way: Files>Build settings… (Some settings that may be useful for you)

When you build it you need to create a folder where unity will put the .exe and the other files in. Then you can run it as a standalone program. (Assuming you build and run for the Windows Standalone)

If you are - in fact - trying to get the Unity editor to close from your UI, then here’s the code to do it:

function Quit(){
    EditorApplication.Exit(0);
}

CAUTION: This will close your unity application and you will lose any unsaved data.

BONUS EDIT: If you just want to stop the application in the editor, you can use the following. Note that it will not work in your builds:

function Quit(){
    EditorApplication.isPlaying = false;
}

If you are in unity ( playmode in unity ), it does not quit, otherwise you would lose your work.
Try run a built version of the game and it should work.

Apply

Application.Quit();

To your code, then go to file then build and run. The code will not work if you’re testing it from the scene editor.

Thank you for this thread. In my case it was an infinite loop making my game hang. Even after detecting the loop none of the above commands exit the app. According to documentation it exits AFTER the end of the current frame. My infinite loop wont allow the reach of that end.

My solution: After the exit command, I prefer UnityEditor.EditorApplication.isPlaying = false, throw an exception.