Most of us, just press the back button on our phone to quit the game, or to go back to the previous page. In this tutorial, we will see how to implement the back button in your Unity game.
I am using Unity 2021.1.13 for this tutorial.
If your intention is to quit the game, when the player presses the back button then Unity has a default function for that
Input.backButtonLeavesApp=true;
Add this line to the update function of your code. It will terminate the application on an android phone when the user presses the back button.
We generally do more than just close the app with the back button. If that is the case the above function will not be of much use.
You can use the following
Input.GetKeyDown(KeyCode.Escape)
This works across all platforms. You can just check if the above function returns true and load your required scene.
Here is an example script.
if(Input.GetKeyDown(KeyCode.Escape))
{
if(SceneManager.GetActiveScene().name=="Game")
{
SceneManager.LoadScene("Menu");
}
if(SceneManager.GetActiveScene().name=="Menu")
{
Application.Quit();
}
}
The above script will take you to the Menu scene if you are in the Game scene and it will quit the application if in Menu scene.
Note: There is a bug in Unity that stops it from reading the keycode. If nothing happens when you press the back button, do the following
- Go to player settings> Other settings.
- Set Active Input Handling to Both.
That’s it for this tutorial. If you have any other questions, feel free to leave a comment below.