Using the Windows Phone Back Button in Unity

Windows Phone apps must support the hardware Back button, and must retain the expected behaviour of returning to the previous screen or exiting an application. Unity has no specific command to support Windows Phone’s Back button, but it’s easy to handle.

Detect the Press

Unity treats the Back button as if it’s a keyboard’s Esc (escape) key, so we just need to detect when this ‘virtual’ Esc key is pressed. Add the following code where you detect user input (typically the Update() method):

#if (UNITY_WP8 && !UNITY_EDITOR) // only run this if the target platform is WP8 and the game is not running in the Unity editor
if (Input.GetKey(KeyCode.Escape))
{
    OnBackButtonPressed();
}
#endif

Create the Handler

The above code is calling a method called OnBackButtonPressed(), which you must now create, and add in code to take the appropriate action (e.g. to navigate to another screen or to close the application).

void OnBackButtonPressed()
{
    // add code here to handle the back button press
    Application.LoadLevel("PreviousScreen");
}

I put the escape key detection code in every scene in a script’s Update() method, and create a specific OnBackButtonPressed() method for each scene. For example, pressing Back from the Settings or About screens should take the player back to the main menu. Maybe in your game pressing back on the game screen should pause the game, then return to the menu if is pressed a second time.

Remember the Guidelines

Keep the user experience and Windows Phone guidelines in mind when implementing the Back button. It must work intuitively. Don’t use the Back button as a control for your game. Use it to take the user back one level in the hierarchy of your game.

Plug time

To see this technique in action in an actual Unity game on Windows Phone you can check out my game: Game of Clowns (AKA Clowntraptions)

Leave a Reply

Your email address will not be published.