AutoAssignInspector.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using UnityEditor;
  5. using UnityEngine;
  6. namespace ERAutoAssign
  7. {
  8. [CustomEditor(typeof(AutoAssign), true)]
  9. public class AutoAssignInspector : UnityEditor.Editor
  10. {
  11. public override void OnInspectorGUI()
  12. {
  13. var targetMb = (MonoBehaviour)target;
  14. if (GUILayout.Button("Auto Assign"))
  15. {
  16. // check my components (Scripts)
  17. foreach (var scriptComponent in targetMb.GetComponents<Component>())
  18. {
  19. // script is [AutoAssignable]
  20. if (Attribute.IsDefined(scriptComponent.GetType(), typeof(AutoAssignable)))
  21. {
  22. Debug.Log(scriptComponent.name + " is AutoAssignable");
  23. var autoFields = scriptComponent.GetType().GetFields().Where(
  24. field => !field.GetCustomAttributes(typeof(ManualAssign)).Any()
  25. ).ToList();
  26. foreach (var field in autoFields)
  27. {
  28. if (!typeof(Component).IsAssignableFrom(field.FieldType)) continue;
  29. bool wasMatched = false;
  30. ForEachChildRecursive(targetMb.transform, (child, depth) =>
  31. {
  32. //Debug.Log($"{field.Name} ({field.FieldType}) <--> {child}");
  33. var childFieldComponent = child.GetComponent(field.FieldType);
  34. if (field.Name == child.name && childFieldComponent)
  35. {
  36. Debug.Log($"AutoAssign: {scriptComponent.name}.{field.Name} = " +
  37. childFieldComponent);
  38. field.SetValue(scriptComponent, childFieldComponent);
  39. wasMatched = true;
  40. }
  41. return wasMatched;
  42. });
  43. if (!wasMatched)
  44. {
  45. field.SetValue(scriptComponent, null);
  46. }
  47. }
  48. }
  49. }
  50. }
  51. }
  52. private void ForEachChildRecursive(Transform parent, Func<Transform, int, bool> func, int curDepth = 0)
  53. {
  54. foreach (var childObj in parent)
  55. {
  56. if (childObj is Transform child)
  57. {
  58. var abort = func.Invoke(child, curDepth);
  59. if (abort)
  60. {
  61. return;
  62. }
  63. if (child.childCount > 0)
  64. {
  65. ForEachChildRecursive(child, func, curDepth++);
  66. }
  67. }
  68. }
  69. }
  70. }
  71. }