EntityContextMenu.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Reflection;
  3. using UnityEditor;
  4. using UnityEngine;
  5. namespace ET
  6. {
  7. public static class EntityContextMenu
  8. {
  9. private static MultiMap<string, AEntityMenuHandler> ACTIONS = new();
  10. private static GenericMenu menu;
  11. static EntityContextMenu()
  12. {
  13. var types = TypeCache.GetTypesWithAttribute<EntityMenuAttribute>();
  14. foreach(var type in types)
  15. {
  16. var menu = type.GetCustomAttribute<EntityMenuAttribute>();
  17. if(menu is null)
  18. {
  19. continue;
  20. }
  21. if(Activator.CreateInstance(type) is not AEntityMenuHandler action)
  22. {
  23. continue;
  24. }
  25. action.menuName = menu.menu_name;
  26. ACTIONS.Add(menu.bind_to.Name, action);
  27. }
  28. }
  29. public static void Show(object entity)
  30. {
  31. if(entity is null)
  32. {
  33. return;
  34. }
  35. string name = entity.GetType().Name;
  36. ACTIONS.TryGetValue(name, out var actions);
  37. if(actions is null)
  38. {
  39. return;
  40. }
  41. menu = new GenericMenu();
  42. foreach(var action in actions)
  43. {
  44. menu.AddItem(
  45. new GUIContent(action.menuName),
  46. false,
  47. delegate(object data)
  48. {
  49. if(data is not Entity callback_data)
  50. {
  51. return;
  52. }
  53. action.OnClick(callback_data);
  54. },
  55. entity
  56. );
  57. }
  58. menu.ShowAsContext();
  59. }
  60. }
  61. }