EntityTreeView.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #if ENABLE_VIEW
  2. using System.Collections.Generic;
  3. using UnityEditor;
  4. using UnityEditor.IMGUI.Controls;
  5. using UnityEngine;
  6. namespace ET
  7. {
  8. public class EntityTreeView: TreeView
  9. {
  10. private EntityTreeViewItem root;
  11. private int id;
  12. private readonly Dictionary<int, Entity> all = new();
  13. private readonly Dictionary<Entity, int> entityHistoryID = new();
  14. public EntityTreeView(TreeViewState state): base(state)
  15. {
  16. Reload();
  17. useScrollView = true;
  18. }
  19. public void Refresh()
  20. {
  21. this.root = BuildRoot() as EntityTreeViewItem;
  22. BuildRows(this.root);
  23. this.Repaint();
  24. }
  25. protected override TreeViewItem BuildRoot()
  26. {
  27. this.id = 0;
  28. this.root = PreOrder(Root.Instance.Scene);
  29. this.root.depth = -1;
  30. SetupDepthsFromParentsAndChildren(this.root);
  31. return this.root;
  32. }
  33. private EntityTreeViewItem PreOrder(Entity root)
  34. {
  35. if(root is null)
  36. {
  37. return null;
  38. }
  39. if(!this.entityHistoryID.TryGetValue(root, out var itemID))
  40. {
  41. this.id++;
  42. itemID = this.id;
  43. this.entityHistoryID[root] = itemID;
  44. }
  45. EntityTreeViewItem item = new(root, itemID);
  46. this.all[itemID] = root;
  47. if(root.Components.Count > 0)
  48. {
  49. foreach(var component in root.Components.Values)
  50. {
  51. item.AddChild(PreOrder(component));
  52. }
  53. }
  54. if(root.Children.Count > 0)
  55. {
  56. foreach(var child in root.Children.Values)
  57. {
  58. item.AddChild(PreOrder(child));
  59. }
  60. }
  61. return item;
  62. }
  63. /// <summary>
  64. /// 处理右键内容
  65. /// </summary>
  66. /// <param name="id"></param>
  67. protected override void ContextClickedItem(int id)
  68. {
  69. if(Event.current.button != 1)
  70. {
  71. return;
  72. }
  73. SingleClickedItem(id);
  74. EntityContextMenu.Show(EntityTreeWindow.VIEW_MONO.Component);
  75. }
  76. /// <summary>
  77. /// 处理左键内容
  78. /// </summary>
  79. /// <param name="id"></param>
  80. protected override void SingleClickedItem(int id)
  81. {
  82. this.all.TryGetValue(id, out Entity entity);
  83. if(entity is null)
  84. {
  85. return;
  86. }
  87. EntityTreeWindow.VIEW_MONO.Component = entity;
  88. Selection.activeObject = null;
  89. // 刷新 Inspector 显示
  90. EditorApplication.delayCall += () => { Selection.activeObject = EntityTreeWindow.VIEW_MONO; };
  91. }
  92. }
  93. }
  94. #endif