Skip to content

Instantly share code, notes, and snippets.

@hariedo
Created November 5, 2023 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hariedo/94ce0cfe6b1c7832d3325365f34f64f2 to your computer and use it in GitHub Desktop.
Save hariedo/94ce0cfe6b1c7832d3325365f34f64f2 to your computer and use it in GitHub Desktop.
A development-time component to watch for Esc and quit playing a Unity game
// QuitAppOnEscape.cs
//
using UnityEngine;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
namespace Screenplay.Workbench
{
//
// Throw this on any always-present game object such as Main Camera
// in any generic super-simple apps for deployment on Android or
// Standalone.
//
// Unity has two input handling setups.
// - the "old" Input manager setup
// - the "new" InputSystem setup
//
// This class uses the new InputSystem if it has been enabled.
//
// Project Settings >
// Player >
// Other Settings >
// Configuration >
// Active Input Handling =
// Both | InputSystem(New) | InputManager(Old)
//
public class QuitAppOnEscape: MonoBehaviour
{
[Tooltip("If true, Quit works in built apps outside editor too.")]
public bool standalone = false;
void Awake()
{
#if UNITY_EDITOR
if (UnityEditor.EditorApplication.isPlaying)
if (!standalone && !Application.isEditor)
Destroy(this);
#endif
}
void Update()
{
#if ENABLE_INPUT_SYSTEM
if (Keyboard.current.escapeKey.wasReleasedThisFrame)
#else
if (Input.GetKeyUp("escape"))
#endif
{
Debug.Log($"Quitting App on Escape Key struck.");
Quit();
}
#if ENABLE_INPUT_SYSTEM
if (Keyboard.current.f12Key.wasReleasedThisFrame)
#else
if (Input.GetKeyUp("f12"))
#endif
{
Debug.Log($"Pausing Game on F12 Key struck.");
Pause();
}
}
void Pause()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPaused = true;
#endif
}
void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#elif UNITY_WEBGL
Application.ExternalEval("window.close();");
#elif UNITY_STANDALONE
Application.Quit();
#else
Application.Quit();
#endif
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment