Developing for Modern Windows

Tips, tricks, and guides for developing on modern Windows platforms

Handling the Windows Phone 8 Back Button in Unity

Windows Phone apps must support the hardware back button. This button gives the user control of their phone, such as easily returning to the previous screen or exiting an application.

Since Unity is cross-platform, there is no specific command to support Windows Phone’s back button, but it’s easy to implement.

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

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. Perhaps in your game pressing back on the game screen should pause the game, then return to the menu if is pressed a second time.

 

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 Clowntraptions:
http://www.grogansoft.com/Presskit/sheet.php?p=clowntraptions

Tags: , ,

Leave a Reply

Your email address will not be published.