AppCallbackListener.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #if ENABLE_MONO && (DEVELOPMENT_BUILD || UNITY_EDITOR)
  2. using System;
  3. using System.Collections;
  4. using UnityEngine;
  5. namespace SingularityGroup.HotReload {
  6. class AppCallbackListener : MonoBehaviour {
  7. /// <summary>
  8. /// Reliable on Android and in the editor.
  9. /// </summary>
  10. /// <remarks>
  11. /// On iOS, OnApplicationPause is not called at expected moments
  12. /// if the app has some background modes enabled in PlayerSettings -Troy.
  13. /// </remarks>
  14. public static event Action<bool> onApplicationPause;
  15. /// <summary>
  16. /// Reliable on Android, iOS and in the editor.
  17. /// </summary>
  18. public static event Action<bool> onApplicationFocus;
  19. static AppCallbackListener instance;
  20. public static AppCallbackListener I => instance;
  21. // Must be called early from Unity main thread (before any usages of the singleton I).
  22. public static AppCallbackListener Init() {
  23. if(instance) return instance;
  24. var go = new GameObject("AppCallbackListener");
  25. go.hideFlags |= HideFlags.HideInHierarchy;
  26. DontDestroyOnLoad(go);
  27. return instance = go.AddComponent<AppCallbackListener>();
  28. }
  29. public bool Paused { get; private set; } = false;
  30. public void DelayedQuit(float seconds) {
  31. StartCoroutine(delayedQuitRoutine(seconds));
  32. }
  33. IEnumerator delayedQuitRoutine(float seconds) {
  34. yield return new WaitForSeconds(seconds);
  35. Application.Quit();
  36. }
  37. void OnApplicationPause(bool paused) {
  38. Paused = paused;
  39. onApplicationPause?.Invoke(paused);
  40. }
  41. void OnApplicationFocus(bool playing) {
  42. onApplicationFocus?.Invoke(playing);
  43. }
  44. }
  45. }
  46. #endif