InstanceUtility.cs 2.5 KB

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