UILayerBehaviour.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace XGame.Framework.UI
  4. {
  5. public class UILayerBehaviour : MonoBehaviour
  6. {
  7. [SerializeField]
  8. private UILayer _layer;
  9. [SerializeField]
  10. private Canvas _uiCanvas;
  11. public Canvas UiCanvas => _uiCanvas;
  12. public Transform UIRoot => _uiCanvas.transform;
  13. private List<IUIPanel> _panels = new List<IUIPanel>();
  14. public UILayer Layer {
  15. get => _layer;
  16. set
  17. {
  18. _layer = value;
  19. _uiCanvas.sortingOrder = (byte)value * 100;
  20. gameObject.name = value.ToString();
  21. }
  22. }
  23. /// <summary>
  24. /// 加入子节点
  25. /// 将Transform移动到本地变换列表的末尾
  26. /// </summary>
  27. /// <param name="child"></param>
  28. public void AddPanel(IUIPanel panel)
  29. {
  30. var panelTr = (panel as UIPanel).transform;
  31. if (!_panels.Contains(panel))
  32. {
  33. panelTr.SetParent(UIRoot, false);
  34. panelTr.position = Vector3.zero;
  35. _panels.Add(panel);
  36. OnChildrenChanged();
  37. }
  38. //将Transform移动到本地变换列表的末尾
  39. panelTr.SetAsLastSibling();
  40. }
  41. /// <summary>
  42. /// 移除子节点
  43. /// </summary>
  44. /// <param name="child"></param>
  45. public void RemovePanel(IUIPanel panel)
  46. {
  47. if (!_panels.Contains(panel))
  48. {
  49. return;
  50. }
  51. _panels.Remove(panel);
  52. (panel as UIPanel).transform.SetParent(null, false);
  53. OnChildrenChanged();
  54. }
  55. private void OnChildrenChanged()
  56. {
  57. _uiCanvas.gameObject.SetActive(_uiCanvas.transform.childCount > 0);
  58. }
  59. }
  60. }