ViewMgr.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.SceneManagement;
  5. using JCUnityLib;
  6. public class ViewMgr : ViewManager<ViewMgr>
  7. {
  8. protected override void OnInited()
  9. {
  10. //设置视图组
  11. SetViewGroup<HomeFrameView>(1);
  12. //场景监听
  13. SceneManager.sceneLoaded += (scene, mode) => {
  14. if (scene.name == "Home") {
  15. ResumeViews(dontDestroyViews);
  16. }
  17. };
  18. SceneManager.sceneUnloaded += (scene) => {
  19. if (scene.name == "Home") {
  20. DestroyAllViewsExcludeDontDestroy();
  21. HideViews(dontDestroyViews);
  22. }
  23. };
  24. }
  25. //以下名称的预制体通过SceneResourceManager获取
  26. HashSet<string> scenePrefabs = new HashSet<string>(new string[] {
  27. //Home
  28. "TopBarView", "HomeView", "GameStartView", "ChallengeOptionView",
  29. "PKGameOptionView", "PKMatchView", "RoleSelectView"
  30. });
  31. protected override GameObject LoadViewPrefab(string viewName)
  32. {
  33. if (scenePrefabs.Contains(viewName)) return SceneResourceManager.Instance.GetPrefab(viewName);
  34. return base.LoadViewPrefab("Home/" + viewName);
  35. }
  36. //以下名称的界面不会随场景销毁而销毁
  37. HashSet<string> dontDestroyViews = new HashSet<string>(new string[] {
  38. //Home
  39. "GameStartView", "ChallengeOptionView", "RoleSelectView", "PKGameOptionView", "PKMatchView"
  40. });
  41. protected override void ShowView(ViewBase viewBase, object[] args)
  42. {
  43. base.ShowView(viewBase, args);
  44. string viewName = viewBase.GetType().Name;
  45. //主要是为了删除名称中的(Clone)
  46. viewBase.gameObject.name = viewName;
  47. //某些界面设置为不销毁
  48. if (dontDestroyViews.Contains(viewName)) viewBase.dontDestroy = true;
  49. //旧版ui适配新ui框架
  50. RectTransform rectTransform = (RectTransform) viewBase.transform;
  51. rectTransform.anchorMin = Vector2.zero;
  52. rectTransform.anchorMax = Vector2.one;
  53. rectTransform.pivot = Vector2.one / 2;
  54. rectTransform.localScale = Vector3.one;
  55. var canvasScaler = rectTransform.GetComponent<UnityEngine.UI.CanvasScaler>();
  56. if (canvasScaler) Destroy(canvasScaler);
  57. //特殊处理
  58. if (viewName == "HomeView") rectTransform.SetSiblingIndex(0);
  59. }
  60. public void ResumeViews(IEnumerable<string> viewNames, params object[] args)
  61. {
  62. foreach (var viewName in viewNames)
  63. {
  64. ViewBase viewBase;
  65. if (viewDict.TryGetValue(viewName, out viewBase)) {
  66. ShowView(viewBase, args);
  67. }
  68. }
  69. }
  70. public void HideViews(IEnumerable<string> viewNames, params object[] args)
  71. {
  72. foreach (var viewName in viewNames)
  73. {
  74. ViewBase viewBase;
  75. if (viewDict.TryGetValue(viewName, out viewBase)) {
  76. HideView(viewBase, false, args);
  77. }
  78. }
  79. }
  80. }