ComponentViewEditor.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #if ENABLE_VIEW
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. using UnityEditor;
  6. using UnityEngine;
  7. namespace ET
  8. {
  9. [CustomEditor(typeof (ComponentView))]
  10. public class ComponentViewEditor: Editor
  11. {
  12. public override void OnInspectorGUI()
  13. {
  14. ComponentView componentView = (ComponentView) target;
  15. Entity component = componentView.Component;
  16. ComponentViewHelper.Draw(component);
  17. }
  18. }
  19. public static class ComponentViewHelper
  20. {
  21. private static readonly List<ITypeDrawer> typeDrawers = new List<ITypeDrawer>();
  22. static ComponentViewHelper()
  23. {
  24. Assembly assembly = typeof (ComponentViewHelper).Assembly;
  25. foreach (Type type in assembly.GetTypes())
  26. {
  27. if (!type.IsDefined(typeof (TypeDrawerAttribute)))
  28. {
  29. continue;
  30. }
  31. ITypeDrawer iTypeDrawer = (ITypeDrawer) Activator.CreateInstance(type);
  32. typeDrawers.Add(iTypeDrawer);
  33. }
  34. }
  35. public static void Draw(Entity entity)
  36. {
  37. try
  38. {
  39. FieldInfo[] fields = entity.GetType()
  40. .GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
  41. EditorGUILayout.BeginVertical();
  42. EditorGUILayout.LongField("InstanceId: ", entity.InstanceId);
  43. EditorGUILayout.LongField("Id: ", entity.Id);
  44. foreach (FieldInfo fieldInfo in fields)
  45. {
  46. Type type = fieldInfo.FieldType;
  47. if (type.IsDefined(typeof (HideInInspector), false))
  48. {
  49. continue;
  50. }
  51. if (fieldInfo.IsDefined(typeof (HideInInspector), false))
  52. {
  53. continue;
  54. }
  55. object value = fieldInfo.GetValue(entity);
  56. foreach (ITypeDrawer typeDrawer in typeDrawers)
  57. {
  58. if (!typeDrawer.HandlesType(type))
  59. {
  60. continue;
  61. }
  62. string fieldName = fieldInfo.Name;
  63. if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
  64. {
  65. fieldName = fieldName.Substring(1, fieldName.Length - 17);
  66. }
  67. value = typeDrawer.DrawAndGetNewValue(type, fieldName, value, null);
  68. fieldInfo.SetValue(entity, value);
  69. break;
  70. }
  71. }
  72. EditorGUILayout.EndVertical();
  73. }
  74. catch (Exception e)
  75. {
  76. UnityEngine.Debug.Log($"component view error: {entity.GetType().FullName} {e}");
  77. }
  78. }
  79. }
  80. }
  81. #endif