Unity: Using the Escape key to escape
Your game is a modern marvel, and it’s hard to imagine why anyone would want to leave, but just in case, here’s how to allow the player to break out.
Currently our project has to be run in Windowed mode to avoid having to use Task Manager or ‘Alt+F4’ to end our game.
We’ll set up the escape key to end the game while it’s running.
In the GameManager script I’ll check for the Escape key in the Update method:
Now if the Escape key is pressed, we call Application.Quit() which ends the application (note this only works for a built version — it won’t work in Play Mode in Unity).
Now if we hit Escape, the game closes:
I’ve also added a text prompt to the Game Over screen:
To allow the player to leave the game from the Main Menu, I’ll add a ‘Quit Game’ button. I start by adding a QuitGame() function in the GameManager script:
This performs the same action as the Escape key.
I duplicate the ‘New Game’ button in the Main Menu scene, change the text to ‘Quit Game’ and change it’s OnClick() function to call Quit Game:
Now if that button is clicked in the Main Menu, again, the application closes:
That’s it for now. We will want to add a return to main menu and possibly a pause screen, but for now our players can easily exit the game.