Search code examples
c#androidunityscriptunity-game-engine

Application quit dialog prompt with buttons on android using Unity 5.3.4 c#


I am new to unity.I need help to set a dialog box prompt with "Yes" & "No" buttons for quitting a game.Dialog box should be generated when user press "back button". Currently i am using this code for quitting but it result in accidental exits.

using UnityEngine;
using System.Collections;
public class AndroidExit : MonoBehaviour
{
#if UNITY_ANDROID
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
            Application.Quit();
    }
#endif
}

Any help will be appreciated.Thank you


Solution

  • Ok found the solution. I hope it may help others like me :)

    Use Mobile Native PopUps plugin (https://unionassets.com/mobile-native-popups)

    1.import it to your project

    2.you have to move files from (Assets/Plugins/StansAssets to → Assets/Plugins).

    3.pass this code to your script(or create a new script)

    using UnityEngine;
    using System.Collections;
    public class AndroidExit : MonoBehaviour
    {    
    #if UNITY_ANDROID
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                MobileNativeDialog dialog = new MobileNativeDialog("Dialog Title", "Dialog message");
                //   Application.Quit();
                dialog.OnComplete += OnDialogClose;
            }
    #endif
        }
        private void OnDialogClose(MNDialogResult result)
        {
            switch (result)
            {
                case MNDialogResult.YES:
                    //Debug.Log("Yes button pressed");
                    Application.Quit();
                    break;
                case MNDialogResult.NO:
                    Debug.Log("No button pressed");
                    break;
            }
        }   
    } 
    

    4.Drag and drop the script to Main Camera in Hierarchy ........