Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

Discussion in 'Android' started by diptiananthan, Mar 18, 2011.

  1. diptiananthan

    diptiananthan

    Joined:
    Jan 21, 2011
    Posts:
    21
    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!!!
     
  2. sawfish

    sawfish

    Joined:
    Feb 12, 2011
    Posts:
    314
    Code (csharp):
    1. if (Application.platform == RuntimePlatform.Android)
    2.         {
    3.             if (Input.GetKey(KeyCode.Escape))
    4.             {
    5.                 // Insert Code Here (I.E. Load Scene, Etc)
    6.                 // OR Application.Quit();
    7.  
    8.                 return;
    9.             }
    10.  
    11.  
     
  3. diptiananthan

    diptiananthan

    Joined:
    Jan 21, 2011
    Posts:
    21
    Hey Sawfishusa,
    It worked:)!!thanx!!
     
  4. suppenhuhn

    suppenhuhn

    Joined:
    Dec 15, 2011
    Posts:
    37
    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 ?
     
  5. suppenhuhn

    suppenhuhn

    Joined:
    Dec 15, 2011
    Posts:
    37
    found it:

    KeyCode.Menu
     
    ZiadMahmoudSayd and BerniceChua like this.
  6. Mariol

    Mariol

    Joined:
    Dec 22, 2009
    Posts:
    42
    Thanks so much for this. Got it to work fine :)
     
  7. Marzoa

    Marzoa

    Joined:
    Dec 2, 2012
    Posts:
    50
    Is there any manner to do the same within the OnGUI method with Event.current?
     
  8. abhishakverma

    abhishakverma

    Joined:
    Feb 27, 2013
    Posts:
    1
    thanks a lot its :p:pwork.
     
  9. UXmanCh

    UXmanCh

    Joined:
    Sep 29, 2015
    Posts:
    1
    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 :)
     
  10. JoeriVDE

    JoeriVDE

    Joined:
    Jan 28, 2015
    Posts:
    6
    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:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. using System.Collections.Generic;
    4.  
    5. //Add this script to your button and call the public methods from the OnClick() event in the inspector
    6. public class PreviousSceneLoader : MonoBehaviour {
    7.    
    8.     //A list to keep track of all the scenes you've loaded so far
    9.     private List<string> previousScenes = new List<string>();
    10.    
    11.     void Awake()
    12.     {
    13.         previousScenes.Add(Application.loadedLevelName); //Add your first scene
    14.         gameObject.SetActive(false); //OPTIONAL: deactivate the button in your first scene, logically because there are no previous scenes  
    15.     }
    16.    
    17.     //Always call this right before you load a new scene from another script (another button for example)
    18.     //Note: Don't forget to activate the button gameobject if you've deactivated it in your first scene,
    19.     //      otherwise you won't be able to call this method if you're using methods like FindObjectOfType<PreviousSceneLoader>()
    20.     //      or GameObject.Find("the button gameobject name").GetComponent<PreviousSceneLoader>()
    21.     public void AddCurrentSceneToLoadedScenes()
    22.     {
    23.         previousScenes.Add(Application.loadedLevelName);
    24.     }
    25.    
    26.     //Call this method from your button OnClick() event system in the inspector
    27.     public void LoadPreviousScene()
    28.     {
    29.         string previousScene = string.Empty;
    30.        
    31.         //Check wether you're not back at your original scene (index 0)
    32.         if(previousScenes.Count > 1)
    33.         {
    34.             previousScene = previousScenes[previousScenes.Count - 1]; //Get the last previously loaded scene name from the list
    35.             previousScenes.RemoveAt(previousScenes.Count - 1); //Remove the last previously loaded scene name from the list
    36.             Application.LoadLevel(previousScene); //Load the previous scene
    37.         }
    38.         else
    39.         {
    40.             previousScene = previousScenes[0]; //0 will always be your first scene
    41.             Application.LoadLevel(previousScene); //Load the previous scene
    42.             gameObject.SetActive(false); //The else is optional if you want the button to be deactivated when returning to the first scene
    43.         }
    44.     }
    45. }
    I haven't tested this yet, feel free to let me know if it works!
     
  11. USAPRODUCER

    USAPRODUCER

    Joined:
    Mar 2, 2016
    Posts:
    5
    I know this is an old post but the code worked great. Thanks sawfish.
     
  12. PHARTGAMES

    PHARTGAMES

    Joined:
    Jan 30, 2013
    Posts:
    5
    Thanks, this works but use GetKeyDown or GetKeyUp instead otherwise GetKey will spam whatever functionality you want to happen while the button is held.
     
  13. yewchunyen

    yewchunyen

    Joined:
    Oct 3, 2017
    Posts:
    8
    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
     
  14. achrafdakdak1

    achrafdakdak1

    Joined:
    Jul 21, 2018
    Posts:
    1
    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 ??
     
  15. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    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.

    Code (CSharp):
    1. if(SceneManager.GetActiveScene().buildIndex <= 3)
    2. {
    3.     backButton.SetActive(false); // Assuming you named your back button variable backButton
    4.     // Or perhaps the smarter choice would just insure the LevelLoad scene is the last scene you can go back
    5. }
    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.
     
  16. Macmac26

    Macmac26

    Joined:
    Feb 27, 2019
    Posts:
    1
    Hi im just new to Unity . I just want to ask where do i put that code from sawfish to make it work?
     
  17. unity_z2KksMoy7kKdtQ

    unity_z2KksMoy7kKdtQ

    Joined:
    Aug 20, 2019
    Posts:
    1
    You need to put his in update function of any script you want it to work in with.
     
  18. DryreL

    DryreL

    Joined:
    Feb 23, 2020
    Posts:
    49
    Thanks
     
  19. luistapia2998

    luistapia2998

    Joined:
    May 20, 2021
    Posts:
    3
    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.