Welcome back! Today we’re going to talk about a simple but important feature. Being able to close out of our game using the Escape key. By default, our game doesn’t know that pressing the escape key should exit our game and if we are running in Full Screen mode this can lead to an issue. To accomplish our goal we want to use a method that Unity provides for us that allows us to exit the running game.
Application.Quit is ignored by the Unity Editor, so we will need to make a build and run it to test this feature.
If we were using the old input manager, we could add an if statement to our Update method in our GameManager class that checks for the press of the escape key and then call application quit if the key press is detected.
We have opted to go with the new Input System in our game so, even though the new system is much more flexible, setting this task up is a little more complicated than in the old system. First we need to open our Input Actions asset and add a new binding for our escape key press. I have added this binding to our UI Action Map, called it Exit Game, and assigned the Escape Key to it for the Keyboard input device.
Now that we have added our new Action to our action map we need to make sure that it is implemented where ever we are using the IUIActions interface. In our case that is on the GameManager Class.
Now that we have our OnExitGame callback method we can implement the Application.Quit functionality. I added a logging statement so that we can still see that the method fires while in the Unity Editor.
The last thing we need to do is connect our callback method with our PlayerActions component in Unity.
That’s it! We’ve added the ability to hit the escape key and exit our application! Next time we will start to look at enhancements I’ll be making as part of the certification portion of the course work that I’m building this game for. If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.