H3XED

How to Handle Android Back Button Event in C# Unity Game Engine (Quit, Pause, Etc)

Nov 23, 2017   Programming   Nick Vogt   Comments (4)
Please note that this post is over a year old and may contain outdated information.
In Unity, the Android back button is treated the same as the "Escape" KeyCode. So in order to do something when the user presses the back button on their Android device, you need to check for the Escape key being pressed down and also make sure the user is on the Android platform (if you're cross-platform).

Here's sample code that quits the app when the back button is pressed:

void Update()
{
    // Make sure user is on Android platform
    if (Application.platform == RuntimePlatform.Android) {
        
        // Check if Back was pressed this frame
        if (Input.GetKeyDown(KeyCode.Escape)) {
            
            // Quit the application
            Application.Quit();
        }
    }
}
Share This Post
Twitter
Unity Guide Books
Unity in Action C# Game Dev
Unity in Action C# Game Dev
See More Details
Unity From Zero to Proficiency
Unity From Zero to Proficiency
See More Details
Unity Cookbook
Unity Cookbook
See More Details
Unity 2D Platformer Guide
Unity 2D Platformer Guide
See More Details

Comments (4)

Nick   Sep 19, 2019
Thanks for the catch!
Firestorm200   Sep 19, 2019
Simple syntax mistake here just wanted to notify you thanks for the snippet if (Input.GetKeyDown(KeyCode.Escape) { -> Missing ')' Should be if (Input.GetKeyDown(KeyCode.Escape)) {
Lopus312   Apr 14, 2019
Exactly what I was looking for, thank you
Pride   Mar 06, 2019
Straight to the Point, I love it 💀✌
Share This Post
Twitter
Unity Guide Books
Unity in Action C# Game Dev
Unity in Action C# Game Dev
See More Details
Unity From Zero to Proficiency
Unity From Zero to Proficiency
See More Details
Unity Cookbook
Unity Cookbook
See More Details
Unity 2D Platformer Guide
Unity 2D Platformer Guide
See More Details
H3XED © Nick Vogt   RSS   Policies   Twitter