InstanceUtility.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. namespace labelUtility
  2. {
  3. using UnityEditor;
  4. using UnityEngine;
  5. using System;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Collections;
  10. using System.Collections.Generic;
  11. using System.Text.RegularExpressions;
  12. public class InstanceUtility
  13. {
  14. private class RelativeObject
  15. {
  16. public int EnumerableIndex;
  17. public bool IsEnumerable;
  18. public string FieldName;
  19. public RelativeObject(string fieldName, string enumerableIndex = null)
  20. {
  21. FieldName = fieldName;
  22. if (enumerableIndex == null)
  23. {
  24. IsEnumerable = false;
  25. }
  26. else
  27. {
  28. EnumerableIndex = int.Parse(enumerableIndex.Substring(5, 1));
  29. IsEnumerable = true;
  30. }
  31. }
  32. public object GetObject(object originObject)
  33. {
  34. object relativeObject = originObject.GetType().GetField(FieldName).GetValue(originObject);
  35. if (IsEnumerable)
  36. {
  37. int index = 0;
  38. foreach (var obj in relativeObject as IEnumerable)
  39. {
  40. if (index == EnumerableIndex)
  41. return obj;
  42. else
  43. index++;
  44. }
  45. }
  46. else
  47. {
  48. return relativeObject;
  49. }
  50. throw new Exception($"{FieldName} {IsEnumerable} {EnumerableIndex}");
  51. }
  52. }
  53. public static object GetObject(FieldInfo fieldInfo, SerializedProperty property)
  54. {
  55. List<string> infos = property.propertyPath.Split('.').ToList();
  56. List<RelativeObject> relativeObjects = new List<RelativeObject>();
  57. for (int i = 0; i < infos.Count; i++)
  58. {
  59. if (i < infos.Count - 1 && infos[i + 1] == "Array")
  60. {
  61. relativeObjects.Add(new RelativeObject(infos[i], infos[i + 2]));
  62. i += 2;
  63. }
  64. else
  65. {
  66. relativeObjects.Add(new RelativeObject(infos[i]));
  67. }
  68. }
  69. object obj = property.serializedObject.targetObject;
  70. foreach (var relativeObject in relativeObjects)
  71. {
  72. obj = relativeObject.GetObject(obj);
  73. }
  74. return obj;
  75. }
  76. public static T GetPropertyDrawerInstance<T>(FieldInfo fieldInfo, SerializedProperty property) where T : class
  77. {
  78. return GetObject(fieldInfo, property) as T;
  79. }
  80. }
  81. }