2023.118: Esc Key Quit in Unity3D
Nobody likes being stuck forever, your game, despite how proud of it you may be, is no exception.
So the other day I ran into this exact issue when I wanted to add fullscreen game play rather than the dinky window my game was starting up in. Low and behold to my surprise, I found out the hard way, getting out of the game was pretty much impossible if I wasn’t a computer literate person. If I wasn’t such a command line warrior wizard the average person would just hit the power button on their computer until the power turned off.
So, how does one add the ability to quit a game in Unity? I had no clue, but I know one thing in #softwareengineering read the docs. After performing “The Most Difficult Search in all of Human History” (https://docs.unity3d.com/ScriptReference/30_search.html?q=Quit) the answer is pretty easy:
Application.Quit();
That’s it. Game Over — well at least we know how to make the game quit but we’ll need to add the key listening. It’s a good thing we have a GameManager
where we can add such logic:
Lines 23–26 are all that’s needed and I really didn’t even need to type them in since the first result in “The Most Difficult Search in all of Human History” query had the code already written ready for the old copy and pasta — but don’t copy and pasta, type that … seriously — don’t get into the habit of copying and pasting code.
Now players can quit the game after panic mashing all the keys until they luckily find the right key, the Esc key to their freedom. But as a great Software Engineer, you write the code that solves the problem:USER STORY: As a USER I want to be able to exit the game.
Maybe a better written USER STORY
ought to have been a feature request along the lines of bring up a settings menu when the user presses the “Esc” key with a button to allow them to Quit the game…but that will be an article for another day.
I will be revisiting a “Settings” interface or Pause Menu or some other such named feature where said “Quit” button will make its appearance.