EditorBase.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. using UnityEditor;
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace Pathfinding {
  6. /// <summary>Helper for creating editors</summary>
  7. [CustomEditor(typeof(VersionedMonoBehaviour), true)]
  8. [CanEditMultipleObjects]
  9. public class EditorBase : Editor {
  10. static System.Collections.Generic.Dictionary<string, string> cachedTooltips;
  11. static System.Collections.Generic.Dictionary<string, string> cachedURLs;
  12. Dictionary<string, SerializedProperty> props = new Dictionary<string, SerializedProperty>();
  13. Dictionary<string, string> localTooltips = new Dictionary<string, string>();
  14. static GUIContent content = new GUIContent();
  15. static GUIContent showInDocContent = new GUIContent("Show in online documentation", "");
  16. static GUILayoutOption[] noOptions = new GUILayoutOption[0];
  17. public static System.Func<string> getDocumentationURL;
  18. protected HashSet<string> remainingUnhandledProperties;
  19. static void LoadMeta () {
  20. if (cachedTooltips == null) {
  21. var filePath = EditorResourceHelper.editorAssets + "/tooltips.tsv";
  22. try {
  23. cachedURLs = System.IO.File.ReadAllLines(filePath).Select(l => l.Split('\t')).Where(l => l.Length == 2).ToDictionary(l => l[0], l => l[1]);
  24. cachedTooltips = new System.Collections.Generic.Dictionary<string, string>();
  25. } catch {
  26. cachedURLs = new System.Collections.Generic.Dictionary<string, string>();
  27. cachedTooltips = new System.Collections.Generic.Dictionary<string, string>();
  28. }
  29. }
  30. }
  31. static string FindURL (System.Type type, string path) {
  32. // Find the correct type if the path was not an immediate member of #type
  33. while (true) {
  34. var index = path.IndexOf('.');
  35. if (index == -1) break;
  36. var fieldName = path.Substring(0, index);
  37. var remaining = path.Substring(index + 1);
  38. var field = type.GetField(fieldName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
  39. if (field != null) {
  40. type = field.FieldType;
  41. path = remaining;
  42. } else {
  43. // Could not find the correct field
  44. return null;
  45. }
  46. }
  47. // Find a documentation entry for the field, fall back to parent classes if necessary
  48. while (type != null) {
  49. var url = FindURL(type.FullName + "." + path);
  50. if (url != null) return url;
  51. type = type.BaseType;
  52. }
  53. return null;
  54. }
  55. static string FindURL (string path) {
  56. LoadMeta();
  57. string url;
  58. cachedURLs.TryGetValue(path, out url);
  59. return url;
  60. }
  61. static string FindTooltip (string path) {
  62. LoadMeta();
  63. string tooltip;
  64. cachedTooltips.TryGetValue(path, out tooltip);
  65. return tooltip;
  66. }
  67. string FindLocalTooltip (string path) {
  68. string result;
  69. if (!localTooltips.TryGetValue(path, out result)) {
  70. var fullPath = target.GetType().Name + "." + path;
  71. result = localTooltips[path] = FindTooltip(fullPath);
  72. }
  73. return result;
  74. }
  75. protected virtual void OnEnable () {
  76. foreach (var target in targets) if (target != null) (target as IVersionedMonoBehaviourInternal).UpgradeFromUnityThread();
  77. }
  78. public sealed override void OnInspectorGUI () {
  79. EditorGUI.indentLevel = 0;
  80. serializedObject.Update();
  81. try {
  82. Inspector();
  83. InspectorForRemainingAttributes(false, true);
  84. } catch (System.Exception e) {
  85. // This exception type should never be caught. See https://docs.unity3d.com/ScriptReference/ExitGUIException.html
  86. if (e is ExitGUIException) throw e;
  87. Debug.LogException(e, target);
  88. }
  89. serializedObject.ApplyModifiedProperties();
  90. if (targets.Length == 1 && (target as MonoBehaviour).enabled) {
  91. var attr = target.GetType().GetCustomAttributes(typeof(UniqueComponentAttribute), true);
  92. for (int i = 0; i < attr.Length; i++) {
  93. string tag = (attr[i] as UniqueComponentAttribute).tag;
  94. foreach (var other in (target as MonoBehaviour).GetComponents<MonoBehaviour>()) {
  95. if (!other.enabled || other == target) continue;
  96. if (other.GetType().GetCustomAttributes(typeof(UniqueComponentAttribute), true).Select(c => (c as UniqueComponentAttribute).tag == tag).Any()) {
  97. EditorGUILayout.HelpBox("This component and " + other.GetType().Name + " cannot be used at the same time", MessageType.Warning);
  98. }
  99. }
  100. }
  101. }
  102. }
  103. protected virtual void Inspector () {
  104. InspectorForRemainingAttributes(true, false);
  105. }
  106. /// <summary>Draws an inspector for all fields that are likely not handled by the editor script itself</summary>
  107. protected virtual void InspectorForRemainingAttributes (bool showHandled, bool showUnhandled) {
  108. if (remainingUnhandledProperties == null) {
  109. remainingUnhandledProperties = new HashSet<string>();
  110. var tp = serializedObject.targetObject.GetType();
  111. var handledAssemblies = new List<System.Reflection.Assembly>();
  112. // Find all types for which we have a [CustomEditor(type)] attribute.
  113. // Unity hides this field, so we have to use reflection to get it.
  114. var customEditorAttrs = this.GetType().GetCustomAttributes(typeof(CustomEditor), true).Cast<CustomEditor>().ToArray();
  115. foreach (var attr in customEditorAttrs) {
  116. var inspectedTypeField = attr.GetType().GetField("m_InspectedType", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  117. var inspectedType = inspectedTypeField.GetValue(attr) as System.Type;
  118. if (!handledAssemblies.Contains(inspectedType.Assembly)) {
  119. handledAssemblies.Add(inspectedType.Assembly);
  120. }
  121. }
  122. bool enterChildren = true;
  123. for (var prop = serializedObject.GetIterator(); prop.NextVisible(enterChildren); enterChildren = false) {
  124. var name = prop.propertyPath;
  125. var field = tp.GetField(name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  126. if (field == null) {
  127. // Can happen for some built-in Unity fields. They are not important
  128. continue;
  129. } else {
  130. var declaringType = field.DeclaringType;
  131. var foundOtherAssembly = false;
  132. var foundThisAssembly = false;
  133. while (declaringType != null) {
  134. if (handledAssemblies.Contains(declaringType.Assembly)) {
  135. foundThisAssembly = true;
  136. break;
  137. } else {
  138. foundOtherAssembly = true;
  139. }
  140. declaringType = declaringType.BaseType;
  141. }
  142. if (foundOtherAssembly && foundThisAssembly) {
  143. // This is a field in a class in a different assembly, which inherits from a class in one of the handled assemblies.
  144. // That probably means the editor script doesn't explicitly know about that field and we should show it anyway.
  145. remainingUnhandledProperties.Add(prop.propertyPath);
  146. }
  147. }
  148. }
  149. }
  150. // Basically the same as DrawDefaultInspector, but with tooltips
  151. bool enterChildren2 = true;
  152. for (var prop = serializedObject.GetIterator(); prop.NextVisible(enterChildren2); enterChildren2 = false) {
  153. var handled = !remainingUnhandledProperties.Contains(prop.propertyPath);
  154. if ((showHandled && handled) || (showUnhandled && !handled)) {
  155. PropertyField(prop.propertyPath);
  156. }
  157. }
  158. }
  159. protected SerializedProperty FindProperty (string name) {
  160. if (!props.TryGetValue(name, out SerializedProperty res)) res = props[name] = serializedObject.FindProperty(name);
  161. if (res == null) throw new System.ArgumentException(name);
  162. return res;
  163. }
  164. protected void Section (string label) {
  165. EditorGUILayout.Separator();
  166. EditorGUILayout.LabelField(label, EditorStyles.boldLabel);
  167. }
  168. /// <summary>Bounds field using center/size instead of center/extent</summary>
  169. protected void BoundsField (string propertyPath) {
  170. PropertyField(propertyPath + ".m_Center", "Center");
  171. var extentsProp = FindProperty(propertyPath + ".m_Extent");
  172. var r = EditorGUILayout.GetControlRect();
  173. var label = EditorGUI.BeginProperty(r, new GUIContent("Size"), extentsProp);
  174. extentsProp.vector3Value = 0.5f * EditorGUI.Vector3Field(r, label, extentsProp.vector3Value * 2.0f);
  175. EditorGUI.EndProperty();
  176. }
  177. protected void FloatField (string propertyPath, string label = null, string tooltip = null, float min = float.NegativeInfinity, float max = float.PositiveInfinity) {
  178. PropertyField(propertyPath, label, tooltip);
  179. Clamp(propertyPath, min, max);
  180. }
  181. protected void FloatField (SerializedProperty prop, string label = null, string tooltip = null, float min = float.NegativeInfinity, float max = float.PositiveInfinity) {
  182. PropertyField(prop, label, tooltip);
  183. Clamp(prop, min, max);
  184. }
  185. protected bool PropertyField (string propertyPath, string label = null, string tooltip = null) {
  186. return PropertyField(FindProperty(propertyPath), label, tooltip, propertyPath);
  187. }
  188. protected bool PropertyField (SerializedProperty prop, string label = null, string tooltip = null) {
  189. return PropertyField(prop, label, tooltip, prop.propertyPath);
  190. }
  191. bool PropertyField (SerializedProperty prop, string label, string tooltip, string propertyPath) {
  192. content.text = label ?? prop.displayName;
  193. content.tooltip = tooltip ?? FindTooltip(propertyPath);
  194. var contextClick = IsContextClick();
  195. EditorGUILayout.PropertyField(prop, content, true, noOptions);
  196. // Disable context clicking on arrays (as Unity has its own very useful context menu for the array elements)
  197. if (contextClick && !prop.isArray && Event.current.type == EventType.Used) CaptureContextClick(propertyPath);
  198. return prop.propertyType == SerializedPropertyType.Boolean ? !prop.hasMultipleDifferentValues && prop.boolValue : true;
  199. }
  200. bool IsContextClick () {
  201. // Capturing context clicks turned out to be a bad idea.
  202. // It prevents things like reverting to prefab values and other nice things.
  203. return false;
  204. // return Event.current.type == EventType.ContextClick;
  205. }
  206. void CaptureContextClick (string propertyPath) {
  207. var url = FindURL(target.GetType(), propertyPath);
  208. if (url != null && getDocumentationURL != null) {
  209. Event.current.Use();
  210. var menu = new GenericMenu();
  211. menu.AddItem(showInDocContent, false, () => Application.OpenURL(getDocumentationURL() + url));
  212. menu.ShowAsContext();
  213. }
  214. }
  215. protected void Popup (string propertyPath, GUIContent[] options, string label = null) {
  216. var prop = FindProperty(propertyPath);
  217. content.text = label ?? prop.displayName;
  218. content.tooltip = FindTooltip(propertyPath);
  219. var contextClick = IsContextClick();
  220. EditorGUI.BeginChangeCheck();
  221. EditorGUI.showMixedValue = prop.hasMultipleDifferentValues;
  222. int newVal = EditorGUILayout.Popup(content, prop.propertyType == SerializedPropertyType.Enum ? prop.enumValueIndex : prop.intValue, options);
  223. if (EditorGUI.EndChangeCheck()) {
  224. if (prop.propertyType == SerializedPropertyType.Enum) prop.enumValueIndex = newVal;
  225. else prop.intValue = newVal;
  226. }
  227. EditorGUI.showMixedValue = false;
  228. if (contextClick && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition)) CaptureContextClick(propertyPath);
  229. }
  230. protected void Mask (string propertyPath, string[] options, string label = null) {
  231. var prop = FindProperty(propertyPath);
  232. content.text = label ?? prop.displayName;
  233. content.tooltip = FindTooltip(propertyPath);
  234. var contextClick = IsContextClick();
  235. EditorGUI.BeginChangeCheck();
  236. EditorGUI.showMixedValue = prop.hasMultipleDifferentValues;
  237. int newVal = EditorGUILayout.MaskField(content, prop.intValue, options);
  238. if (EditorGUI.EndChangeCheck()) {
  239. prop.intValue = newVal;
  240. }
  241. EditorGUI.showMixedValue = false;
  242. if (contextClick && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition)) CaptureContextClick(propertyPath);
  243. }
  244. protected void IntSlider (string propertyPath, int left, int right) {
  245. var contextClick = IsContextClick();
  246. var prop = FindProperty(propertyPath);
  247. content.text = prop.displayName;
  248. content.tooltip = FindTooltip(propertyPath);
  249. EditorGUILayout.IntSlider(prop, left, right, content, noOptions);
  250. if (contextClick && Event.current.type == EventType.Used) CaptureContextClick(propertyPath);
  251. }
  252. protected void Slider (string propertyPath, float left, float right) {
  253. var contextClick = IsContextClick();
  254. var prop = FindProperty(propertyPath);
  255. content.text = prop.displayName;
  256. content.tooltip = FindTooltip(propertyPath);
  257. EditorGUILayout.Slider(prop, left, right, content, noOptions);
  258. if (contextClick && Event.current.type == EventType.Used) CaptureContextClick(propertyPath);
  259. }
  260. protected void Clamp (SerializedProperty prop, float min, float max = float.PositiveInfinity) {
  261. if (!prop.hasMultipleDifferentValues) prop.floatValue = Mathf.Clamp(prop.floatValue, min, max);
  262. }
  263. protected void Clamp (string name, float min, float max = float.PositiveInfinity) {
  264. Clamp(FindProperty(name), min, max);
  265. }
  266. protected void ClampInt (string name, int min, int max = int.MaxValue) {
  267. var prop = FindProperty(name);
  268. if (!prop.hasMultipleDifferentValues) prop.intValue = Mathf.Clamp(prop.intValue, min, max);
  269. }
  270. }
  271. }