InterfaceDrawer.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using UnityEngine;
  5. using UnityEditor;
  6. using System.Collections.Generic;
  7. using Rokid.UXR.Interaction;
  8. namespace Rokid.UXR.Editor
  9. {
  10. /// <summary>
  11. /// This property drawer is the meat of the interface support implementation. When
  12. /// the value of field with this attribute is modified, the new value is tested
  13. /// against the interface expected. If the component matches, the new value is
  14. /// accepted. Otherwise, the old value is maintained.
  15. /// </summary>
  16. [CustomPropertyDrawer(typeof(InterfaceAttribute))]
  17. public class InterfaceDrawer : PropertyDrawer
  18. {
  19. private int _filteredObjectPickerID;
  20. private static readonly Type[] _singleMonoBehaviourType = new Type[1] { typeof(MonoBehaviour) };
  21. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  22. {
  23. _filteredObjectPickerID = GUIUtility.GetControlID(FocusType.Passive);
  24. if (property.serializedObject.isEditingMultipleObjects) return;
  25. if (property.propertyType != SerializedPropertyType.ObjectReference)
  26. {
  27. EditorGUI.LabelField(position, label.text, "InterfaceType Attribute can only be used with MonoBehaviour Components.");
  28. return;
  29. }
  30. EditorGUI.BeginProperty(position, label, property);
  31. Type[] attTypes = GetInterfaceTypes(property);
  32. // Pick a specific component
  33. MonoBehaviour oldComponent = property.objectReferenceValue as MonoBehaviour;
  34. string oldComponentName = "";
  35. GameObject temporaryGameObject = null;
  36. string attTypesName = GetTypesName(attTypes);
  37. if (Event.current.type == EventType.Repaint)
  38. {
  39. if (oldComponent == null)
  40. {
  41. temporaryGameObject = new GameObject("None (" + attTypesName + ")");
  42. oldComponent = temporaryGameObject.AddComponent<InterfaceMono>();
  43. }
  44. else
  45. {
  46. oldComponentName = oldComponent.name;
  47. oldComponent.name = oldComponentName + " (" + attTypesName + ")";
  48. }
  49. }
  50. Component currentComponent = EditorGUI.ObjectField(position, label, oldComponent, typeof(Component), true) as Component;
  51. int objectPickerID = GUIUtility.GetControlID(FocusType.Passive) - 1;
  52. ReplaceObjectPickerForControl(attTypes, objectPickerID);
  53. if (Event.current.commandName == "ObjectSelectorUpdated"
  54. && EditorGUIUtility.GetObjectPickerControlID() == _filteredObjectPickerID)
  55. {
  56. UnityEngine.Object pickedObject = EditorGUIUtility.GetObjectPickerObject();
  57. if (pickedObject is GameObject)
  58. {
  59. currentComponent = (pickedObject as GameObject).transform;
  60. }
  61. else
  62. {
  63. currentComponent = pickedObject as Component;
  64. }
  65. }
  66. MonoBehaviour currentMono = currentComponent as MonoBehaviour;
  67. if (Event.current.type == EventType.Repaint)
  68. {
  69. if (temporaryGameObject != null)
  70. GameObject.DestroyImmediate(temporaryGameObject);
  71. else
  72. oldComponent.name = oldComponentName;
  73. }
  74. // If a component is assigned, make sure it is the interface we are looking for.
  75. if (currentMono != null)
  76. {
  77. // Make sure component is of the right interface
  78. if (!IsAssignableFromTypes(currentMono.GetType(), attTypes))
  79. // Component failed. Check game object.
  80. foreach (Type attType in attTypes)
  81. {
  82. currentMono = currentMono.gameObject.GetComponent(attType) as MonoBehaviour;
  83. if (currentMono == null)
  84. {
  85. break;
  86. }
  87. }
  88. // Item failed test. Do not override old component
  89. if (currentMono == null)
  90. {
  91. if (oldComponent != null && !IsAssignableFromTypes(oldComponent.GetType(), attTypes))
  92. {
  93. temporaryGameObject = new GameObject("None (" + attTypesName + ")");
  94. MonoBehaviour temporaryComponent = temporaryGameObject.AddComponent<InterfaceMono>();
  95. currentMono = EditorGUI.ObjectField(position, label, temporaryComponent, typeof(MonoBehaviour), true) as MonoBehaviour;
  96. GameObject.DestroyImmediate(temporaryGameObject);
  97. }
  98. }
  99. }
  100. else if (currentComponent is Transform)
  101. {
  102. // If assigned component is a Transform, this means a GameObject was dragged into the property field.
  103. // Find all matching components on the transform's GameObject and open the picker window.
  104. List<MonoBehaviour> monos = new List<MonoBehaviour>();
  105. monos.AddRange(currentComponent.gameObject.GetComponents<MonoBehaviour>().
  106. Where((mono) => IsAssignableFromTypes(mono.GetType(), attTypes)));
  107. if (monos.Count > 1)
  108. {
  109. EditorApplication.delayCall += () => InterfacePicker.Show(property, monos);
  110. }
  111. else
  112. {
  113. currentMono = monos.Count == 1 ? monos[0] : null;
  114. }
  115. }
  116. if (currentComponent == null || currentMono != null)
  117. {
  118. property.objectReferenceValue = currentMono;
  119. }
  120. EditorGUI.EndProperty();
  121. }
  122. private bool IsAssignableFromTypes(Type source, Type[] targets)
  123. {
  124. foreach (Type t in targets)
  125. {
  126. if (!t.IsAssignableFrom(source))
  127. {
  128. return false;
  129. }
  130. }
  131. return true;
  132. }
  133. private static string GetTypesName(Type[] attTypes)
  134. {
  135. if (attTypes.Length == 1)
  136. {
  137. return GetTypeName(attTypes[0]);
  138. }
  139. string typesString = "";
  140. for (int i = 0; i < attTypes.Length; i++)
  141. {
  142. if (i > 0)
  143. {
  144. typesString += ", ";
  145. }
  146. typesString += GetTypeName(attTypes[i]);
  147. }
  148. return typesString;
  149. }
  150. private static string GetTypeName(Type attType)
  151. {
  152. if (!attType.IsGenericType)
  153. {
  154. return attType.Name;
  155. }
  156. var genericTypeNames = attType.GenericTypeArguments.Select(GetTypeName);
  157. return $"{attType.Name}<{string.Join(", ", genericTypeNames)}>";
  158. }
  159. private Type[] GetInterfaceTypes(SerializedProperty property)
  160. {
  161. InterfaceAttribute att = (InterfaceAttribute)attribute;
  162. Type[] t = att.Types;
  163. if (!String.IsNullOrEmpty(att.TypeFromFieldName))
  164. {
  165. var thisType = property.serializedObject.targetObject.GetType();
  166. while (thisType != null)
  167. {
  168. var referredFieldInfo = thisType.GetField(att.TypeFromFieldName,
  169. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  170. if (referredFieldInfo != null)
  171. {
  172. t = new Type[1] { referredFieldInfo.FieldType };
  173. break;
  174. }
  175. thisType = thisType.BaseType;
  176. }
  177. }
  178. return t ?? _singleMonoBehaviourType;
  179. }
  180. void ReplaceObjectPickerForControl(Type[] attTypes, int replacePickerID)
  181. {
  182. var currentObjectPickerID = EditorGUIUtility.GetObjectPickerControlID();
  183. if (currentObjectPickerID != replacePickerID)
  184. {
  185. return;
  186. }
  187. var derivedTypes = TypeCache.GetTypesDerivedFrom(attTypes[0]);
  188. HashSet<Type> validTypes = new HashSet<Type>(derivedTypes);
  189. for (int i = 1; i < attTypes.Length; i++)
  190. {
  191. var derivedTypesIntersect = TypeCache.GetTypesDerivedFrom(attTypes[i]);
  192. validTypes.IntersectWith(derivedTypesIntersect);
  193. }
  194. //start filter with a long empty area to allow for easy clicking and typing
  195. var filterBuilder = new System.Text.StringBuilder(" ");
  196. foreach (Type type in validTypes)
  197. {
  198. if (type.IsGenericType)
  199. {
  200. continue;
  201. }
  202. filterBuilder.Append("t:" + type.FullName + " ");
  203. }
  204. string filter = filterBuilder.ToString();
  205. EditorGUIUtility.ShowObjectPicker<Component>(null, true, filter, _filteredObjectPickerID);
  206. }
  207. }
  208. public sealed class InterfaceMono : MonoBehaviour { }
  209. }