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:
- Add a canvas with a text (e.g. “Do you want to quit?”) and two buttons (“yes” and “no”) under the rocket prefab.
- Add three fields in ApplicationQuit (Canvas, YesButton, NoButton).
- Hook up the canvas and the buttons.
- Hide the canvas by default.
- When a user presses Escape, toggle the canvas visibility (it behaves nicely since hitting Escape twice will re-hide the prompt)
- If user hits “no”, hide the canvas.
- 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:
Here is the binding of the three fields:
Here is the in-game screenshot:
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!