Show UI before quitting

Quitting the game on hitting the Escape key is all fine for an exercise, but would be very frustrating to players of the real game. To make it a bit more user-friendly, consider doing the following:

  1. Add a canvas with a text (e.g. “Do you want to quit?”) and two buttons (“yes” and “no”) under the rocket prefab.
  2. Add three fields in ApplicationQuit (Canvas, YesButton, NoButton).
  3. Hook up the canvas and the buttons.
  4. Hide the canvas by default.
  5. When a user presses Escape, toggle the canvas visibility (it behaves nicely since hitting Escape twice will re-hide the prompt)
  6. If user hits “no”, hide the canvas.
  7. If user hits “yes”, quit.

Here is my full code (as a bonus, quitting also works in the editor):

using UnityEngine;
using UnityEngine.UI;

public class ApplicationQuit : MonoBehaviour
{
    [SerializeField] public GameObject QuitCanvas;
    [SerializeField] public Button YesButton;
    [SerializeField] public Button NoButton;

    void Start()
    {
        YesButton.GetComponent<Button>().onClick.AddListener(() =>
        {
            #if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
            #else
            Application.Quit();
            #endif
        });
        NoButton.GetComponent<Button>().onClick.AddListener(() => { QuitCanvas.SetActive(false); });
    }

    void Update()
    {
        if (Input.GetKeyUp(KeyCode.Escape))
        {
            QuitCanvas.SetActive(!QuitCanvas.activeInHierarchy);
        }
    }
}

Here is the part of the rocket prefab that has the UI:
image

Here is the binding of the three fields:
image

Here is the in-game screenshot:

image

Important: when you create UI buttons, Unity will automatically add an EventSystem component. Be careful - if it’s not included in your prefab, the buttons won’t work in other scenes!

1 Like

He hasn’t gone over canvases yet but yeah I agree a confirmation screen is always a must if you’re going to attach quitting the game to a hotkey.

Privacy & Terms