How to program the 'back' button of android phone through unity?

Hey guys,
I want to program my back button on the phone,to go back from the current scene to the previous scene.It is possible to do it through unity na???Has anyone tried to do this???I have been trying this but all methods involve linking to eclipse.Can’t we do it from unity without eclipse???
Thanks n regards!!!

if (Application.platform == RuntimePlatform.Android)
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                // Insert Code Here (I.E. Load Scene, Etc)
                // OR Application.Quit();

                return;
            }
19 Likes

Hey Sawfishusa,
It worked:)!!thanx!!

Yes that’s what i was looking for … THANK YOU!

But one more question: The Galaxy Tab has got a second “button” for options - but i can’t find a options key in the input managerlist for special keys.
Anyone a idea ?

found it:

KeyCode.Menu

2 Likes

Thanks so much for this. Got it to work fine :slight_smile:

Is there any manner to do the same within the OnGUI method with Event.current?

thanks a lot its :p:pwork.

i am having a problem in my buttons in ui as i creat a button “back” and i want this button to stay active in every scene . and when i press the back button it shold take me to previous screen or level selection menu … if anybody can help let me know … thankx :slight_smile:

Well I would suggest you create a new UI Canvas specifically for your ‘Back Button’. Then create a DontDestroyOnLoad script, add it to the parent canvas of the Back button. This way it won’t get destroyed when a new scene loads.

As for going back to the previous level each time you hit the Back Button, on a normal UI button something like this might work:

using UnityEngine;

using System.Collections.Generic;

//Add this script to your button and call the public methods from the OnClick() event in the inspector
public class PreviousSceneLoader : MonoBehaviour {
   
    //A list to keep track of all the scenes you've loaded so far
    private List<string> previousScenes = new List<string>();
   
    void Awake()
    {
        previousScenes.Add(Application.loadedLevelName); //Add your first scene
        gameObject.SetActive(false); //OPTIONAL: deactivate the button in your first scene, logically because there are no previous scenes   
    }
   
    //Always call this right before you load a new scene from another script (another button for example)
    //Note: Don't forget to activate the button gameobject if you've deactivated it in your first scene,
    //      otherwise you won't be able to call this method if you're using methods like FindObjectOfType<PreviousSceneLoader>()
    //      or GameObject.Find("the button gameobject name").GetComponent<PreviousSceneLoader>()
    public void AddCurrentSceneToLoadedScenes()
    {
        previousScenes.Add(Application.loadedLevelName);
    }
   
    //Call this method from your button OnClick() event system in the inspector
    public void LoadPreviousScene()
    {
        string previousScene = string.Empty;
       
        //Check wether you're not back at your original scene (index 0)
        if(previousScenes.Count > 1)
        {
            previousScene = previousScenes[previousScenes.Count - 1]; //Get the last previously loaded scene name from the list
            previousScenes.RemoveAt(previousScenes.Count - 1); //Remove the last previously loaded scene name from the list
            Application.LoadLevel(previousScene); //Load the previous scene
        }
        else
        {
            previousScene = previousScenes[0]; //0 will always be your first scene
            Application.LoadLevel(previousScene); //Load the previous scene
            gameObject.SetActive(false); //The else is optional if you want the button to be deactivated when returning to the first scene
        }
    }
}

I haven’t tested this yet, feel free to let me know if it works!

3 Likes

I know this is an old post but the code worked great. Thanks sawfish.

Thanks, this works but use GetKeyDown or GetKeyUp instead otherwise GetKey will spam whatever functionality you want to happen while the button is held.

4 Likes

Hi all, I got a question as too new to unity. Meanwhile, i need to create another new script for only the coding for this function and add to asset folder? Or what should be the proper path. I am not sure where to put those lines.

Thanks

Cheers everybody!

Thanks for a lot for the great threads. Yet, I still have a lil problem. Could anyone have any idea about how to get back within the same scene pressing the back button on the android device ??

You can do that easily by using SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);

That line of code should take you back one scene each click.

Your level select menu could just be the last scene you want it to go back to. For example, if your build index is 3 and that’s as far back as you want it to go, use logic to not allow further BACK.

if(SceneManager.GetActiveScene().buildIndex <= 3)
{
    backButton.SetActive(false); // Assuming you named your back button variable backButton
    // Or perhaps the smarter choice would just insure the LevelLoad scene is the last scene you can go back
}

Also note you can literally copy/paste the button into each scene within the hierarchy and it’ll take on the same Transform without having to re-align each new scene.

Hi im just new to Unity . I just want to ask where do i put that code from sawfish to make it work?

You need to put his in update function of any script you want it to work in with.

Thanks

It works, only to be clear, Application functions had been deprecated in favor of SceneManager. I add the scene before load the next, that implies that I have an empty list first and check if list isn’t empty to load previous scene. You can see the code here.
I combine your solution with the Stateless Pattern forked from tomlarkworthy.