The Escape Button: How to Close a Unity Application with Input

Blake Zoeckler
3 min readMay 23, 2021

I mentioned in my article about standalone builds that we wouldn’t want to create a fullscreen application because the player would have no way to get out of it. Now it’s time to fix that.

First we will need to setup the Input Manager with a button that will allow the user to quit the application. We can use “Cancel” for this, since it’s already assigned to the escape key. We can also assign it to “joystick button 6” which will allow a controller’s back button to also quit the game.

Now for the code. The GameManager class is perfect for this, since that’s what’s supposed to control important game commands like exiting. We can just add a new if-statement that checks for the Cancel input, and tell the Application to quit.

Now if we were to make a fullscreen standalone application of this game, we would have an easy way to quit out of it!

However, there’s a downside. Calling Application.Quit has adverse effects on other possible builds. When escape is pressed when the WebGL version is playing, we get a nasty looking error:

How can we allow the application to quit in one build but not quit in another? There actually happens to be an easy solution: Platform Dependent Compilation. We can insert a command that looks sort of like an if-statement:

What it looks like in the Windows Standalone platform.
Here’s what it looks like in the WebGL platform.

This allows us to control what code is actually compiled on certain platforms. In this case, the cancel button check only ever exists when we are building to a standalone application. For the WebGL version, the code is greyed out and treated like it doesn’t even exist.

That’s all there is to it. We now have good application-quitting behavior no matter what platform we are building to!

--

--

Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.