PersistenHandler.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.SceneManagement;
  5. //持久化的处理脚本,在app启动时就应开始常驻
  6. public class PersistenHandler : MonoBehaviour
  7. {
  8. public MenuBackController menuBackCtr = new MenuBackController();
  9. public static PersistenHandler ins;
  10. public static void Init() {
  11. if (ins) return;
  12. GameObject obj = new GameObject("PersistenHandler");
  13. ins = obj.AddComponent<PersistenHandler>();
  14. DontDestroyOnLoad(obj);
  15. }
  16. void Update()
  17. {
  18. menuBackCtr.Update();
  19. }
  20. }
  21. public class MenuBackController {
  22. static List<string> NeedBackGameScenes = new List<string>(new string[] { "DuckHunter", "WildAttack", "FruitMaster" });
  23. public List<MenuBackInterface> views = new List<MenuBackInterface>();
  24. long lastPressExitTime = 0;
  25. public void Update()
  26. {
  27. if (Input.GetKeyDown(KeyCode.Escape)) HandleKeyDownEscape();
  28. }
  29. public void HandleKeyDownEscape()
  30. {
  31. long lastLast = lastPressExitTime;
  32. lastPressExitTime = JCUnityLib.TimeUtils.GetTimestamp();
  33. if (lastPressExitTime - lastLast < 10 * 1000)
  34. {
  35. OnTwiceBack();
  36. }
  37. else
  38. {
  39. OnOnceBack();
  40. }
  41. }
  42. private void BanTwice() {
  43. lastPressExitTime = 0;
  44. }
  45. public void OnOnceBack() {
  46. var sceneName = SceneManager.GetActiveScene().name;
  47. if (sceneName == "Entry") {
  48. BanTwice();
  49. Debug.Log("菜单退出: " + sceneName);
  50. Application.Quit();
  51. return;
  52. }
  53. if (sceneName.StartsWith("Game") || NeedBackGameScenes.Contains(sceneName)) {
  54. BanTwice();
  55. Debug.Log("菜单返回主页");
  56. SceneManager.LoadScene("Home", LoadSceneMode.Single);
  57. return;
  58. }
  59. if (views.Count > 0) {
  60. BanTwice();
  61. MenuBackInterface i = views[views.Count - 1];
  62. if (i.OnMenuBack()) {
  63. views.Remove(i);
  64. Debug.Log("菜单返回成功: " + i);
  65. } else {
  66. Debug.Log("菜单返回失败: " + i);
  67. }
  68. return;
  69. }
  70. Debug.Log("菜单退出APP询问");
  71. PopupMgr.ins.ShowTip(TextAutoLanguage2.GetTextByKey("tip_phone-menu-back_quit-app"));
  72. }
  73. private void OnTwiceBack() {
  74. Debug.Log("菜单退出APP");
  75. Application.Quit();
  76. }
  77. }
  78. public interface MenuBackInterface {
  79. public bool OnMenuBack();
  80. }