There is No Escape!… Key

When playing the Standalone Build of your game, you may notice there is no way to close the game from within the game. Let’s fix that, making it easier for the player to exit the game. To add this functionality is pretty simple.

In the GameManager script, add an if statement to Update that looks for user input of the Escape key being pressed. If so, call Application.Quit(); to close the game. The Application class is used to access and control the run-time data of the game. The Quit function of the Application class shuts down the running application, which is the game, but if you try to test this in Unity, it will not work because the Quit call is ignored and only works in the Build of the game.

If you make a new Build and play it, now hitting the Escape key will close the game. To get this functionality in Unity, we have to add a bit more code.

In the GameManager script, add using UnityEditor; at the top of the script to access the UnityEditor namespace.

Next in Update, inside the if statement checking for the Escape keypress, add EditorApplication.ExitPlayMode();. The EditorApplication class works very much like the Application class, but it is for Unity Editor. The ExitPlayMode function is pretty self-explanatory. It exits Play Mode.

With that added code, you can now exit Play Mode with the Escape key.

If you want to get fancy, you can use Unity’s Platform Dependent Compilation feature so that Unity will ignore the code that is not for the platform it is compiling for, which allows you to make parts of your code specific to a platform.

To do this, add #if UNITY_EDITOR, #else in between, and close it off with #endif. What this is doing is telling Unity only to include EditorApplication.ExitPlayMode in the Unity Editor, and for everything else, include Application.Quit.

Unity Developer, Software Engineer, Game Designer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store