Nice way to let the quit button to work in the editor

Hello,

With the following you can let the quit button work in the Editor.


    public void QuitRequest()
    {
        Debug.Log("Quit requested");
#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#else
        Application.Quit();
#endif
    }

Greetings Bert.

8 Likes

Yay! I tried it and it works!!!

Thankyou :sunglasses:.

Dunno how but it worked! Cool. :slight_smile:

Hey guys!
It works but I don’t know why, could someone explain please?
Thanx

Hello All,

Let me explain!
The code in green are what unity calls "Platform dependent compilation"
They are just “Preprocessor Directives” in C#
This testing happens before you compile and run the code. So the code above can be 1 of 2 ways.

  1. If the code is run in the Unity Editor (#if UNITY_EDITOR is true)
    the code becomes.

    public void QuitRequest()
    {
    Debug.Log(“Quit requested”);
    UnityEditor.EditorApplication.isPlaying = false;
    }

  2. if the code is run as an application (#if UNITY_EDITOR is false)
    the code becomes.

    public void QuitRequest()
    {
    Debug.Log(“Quit requested”);
    Application.Quit();
    }

I hope you understand this.

Greetings,
Bert Berrevoets

3 Likes

The #if UNITY_EDITOR is an kind of Platform Dependent Compilation, this prevents anything that isn’t the UnityEditor to run the code. You could do the same with Android for example, to make something run only if it is executed within an Android device.

The UnityEditor.EditorApplication.isPlaying is the bool responsible for saying if the application is actually running or not, it only works when you are executing within the unity editor, if you change it to false it will stop the application as observed. And the Application.Quit() only works for actually builds, and don’t work within the editor alone.

These special if/else statements are there only to make sure that the right method will be used to stop the application regardless if you are within the Editor or in the actual build. You could for example add one more if to handle the case when the player clicks on the quit button within an webgl build, and you can try a different approach to those two methods since probably neither would work for Webgl

3 Likes

Thank you for explaining.
Unfortunately, my English is not good enough.

1 Like

Better than mine :slight_smile:
I have not seen your reply by the time that I wrote mine, sorry for duplicating it :sweat_smile:

1 Like

Privacy & Terms