Time To Quit
Adding the quit feature when escape is pressed
Adding a quit function may seem asinine, but if you build your game out to take the whole screen, there is no other way to shut it down, except for opening the task manager. And who wants to do that?
Unity has a built in function called Application.Quit. It's a simple function and we can implement it just as easily.
We used 2 different scripts when we started the game. We have our Main Menu script which gives us the functions for our new game button. And we have our Game Manager script, which gives us the functionality for starting the game and spawning the enemies.
If we want to quit after the game is over, we need to set up that function in the Game Manager.
In the update method, we’ll add an if statement. We use the GetKeyDown function to check if the escape key is pressed. If the escape key is pressed during the game, then we use Application.quit to end the game and close the window.
If we are still on the main menu screen, this won’t work because the game manager is not active yet. So, if we want to quit from the main menu, we need something else.
I created a button in my UI manager and called it Quit button. To do that we need to select the Canvas object in our Hierarchy, right click, scroll down to UI, and select Button-TextMeshPro.
Rename the button to Quit_Button. In the button component, you can set the functionality of your button. I made the Highlighted color red, so that when the mouse cursor is over the button it turns red.
Select the drop down arrow and select the child text object. This is where you can ad text to your button.
With the Button object selected, you can adjust the size and position in the scene view.
Now that we have our button, we need the logic to make it work.
We can look at our new game button and see that we set a condition that references our main menu script. The condition is onClick(), it will be active on runtime only, and it is calling the load game method from the main menu script.
On our main menu script, we can create a new function and call it QuitGame(). Inside that method we use Application.quit.
On our quit button, we can add a condition. We use the canvas game object as our reference. For the function, we select the drop down menu, scroll down to main menu and select our quit game method from the list.
NOTE: the Application.Quit() function will not work inside Unity. If you look in the API, you will see that this function is ignored by the editor. To test this function, build out the game for Windows.