In this article we see the instructions we need execute in order to quit the game in Unity, then we will make a button call the exit function when pressed.
In the following video you can see the complete process in which we see how to close the game in Unity, from the creation of a simple Canvas to test the function, to the script with the necessary functions.
Includes Button Setup
A SHORT BREAK WITH THE LATEST NEWS
LET'S CONTINUE WITH THE ARTICLE
User Interface for Testing
We are going to use a very simple user interface that will consist of a button that when pressed will execute the function to close the game.
Script with the Function to Quit the Game
We will create a script called “Control” that will be assigned to any GameObject in the hierarchy and will contain a public function called “Exit” (see what is a method in programming and how to use it).
Within the “Exit” method we will place a single instruction that will be in charge of closing the game.
The idea is that the button on the user interface will execute this function when it is pressed.
For this we select the button in the hierarchy and in the inspector, in the OnClick section we click on the little plus sign to add a new field, we drag the GameObject that has the public function to close the game and using the drop-down menu we look for this function in the list.
We’ve seen very simply how to close the game at Unity. For this we must execute the “Application.Quit()” instruction somewhere in the code. In this case we execute it when we press the exit button of the user interface, but we could do it in different ways.
Now it is time to think about what tasks we should carry out when closing the game and make sure they are executed before the Quit instruction. For example, what information should we save to retrieve in the next session?