The Escape Button is a Feature
Objective: implement a feature to allow the player to quit the Unity game from a full-screen setting using the Escape key.
This will be a very short article on how to implement the use of a keypress to quit your application in Unity. By default, deployed applications do not come with a built-in feature allowing them to quit from a full-screen play mode. In order to do this, you need to program it into your game.
Unity provides us with an easy solution using Application.Quit.
Inside your Game Manager, simply add another IF statement looking for the Escape key getting pressed, and upon detection execute the public static void Quit().
I also added a text field to inform the player whenever the game is over that the option exists to exit by pressing the ESC key.
If you are running a Main Menu scene, it’s a good idea to add this functionality in case the player wishes to exit back out to the OS without starting a new game.
I opted to do this. First, I switched over to my Main Menu scene and added a public void QuitGame() method to the MainMenu script.
I then duplicated my “New_Game_btn” button, renamed it to “Quit_Game_btn”, and changed the On Click() setting to execute the MainMenu.QuitGame method. Since pressing the ESC key doesn’t quit the game on the Main Menu splash screen, but uses an “EXIT” button instead, I added some additional text to inform the player to avoid any confusion.
There you have it. You may now exit the game back to your OS by either selecting the “EXIT” button on the Main Menu screen or by pressing ESC anytime during a game session. Hope you found this helpful. Thanks for reading! :)