SampleReadMe.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. #pragma warning disable CS0649 // Field is never assigned to, and will always have its default value.
  3. #if UNITY_EDITOR
  4. using System;
  5. using System.IO;
  6. using UnityEditor;
  7. using UnityEditor.SceneManagement;
  8. using UnityEditorInternal;
  9. using UnityEngine;
  10. using UnityEngine.SceneManagement;
  11. using Object = UnityEngine.Object;
  12. namespace Animancer.Samples
  13. {
  14. /// <summary>[Editor-Only] A component which explains a sample scene.</summary>
  15. /// https://kybernetik.com.au/animancer/api/Animancer.Samples/SampleReadMe
  16. [AnimancerHelpUrl(typeof(SampleReadMe))]
  17. [AddComponentMenu("")]
  18. public class SampleReadMe : MonoBehaviour
  19. {
  20. /************************************************************************************************************************/
  21. [SerializeField, Multiline(10)]
  22. private string _Text;
  23. /************************************************************************************************************************/
  24. #if UNITY_IMGUI
  25. /************************************************************************************************************************/
  26. [InitializeOnLoadMethod]
  27. private static void InitializeAutoSelect()
  28. {
  29. bool isInEditMode = !EditorApplication.isPlayingOrWillChangePlaymode;
  30. EditorApplication.playModeStateChanged += change =>
  31. {
  32. switch (change)
  33. {
  34. case PlayModeStateChange.EnteredEditMode:
  35. isInEditMode = true;
  36. break;
  37. default:
  38. isInEditMode = false;
  39. break;
  40. }
  41. };
  42. EditorSceneManager.activeSceneChangedInEditMode += (from, to) =>
  43. {
  44. if (!isInEditMode)
  45. return;
  46. Object selected = Selection.activeObject;
  47. if (selected != null && selected is not SceneAsset)
  48. return;
  49. foreach (GameObject gameObject in to.GetRootGameObjects())
  50. {
  51. if (gameObject.TryGetComponent(out SampleReadMe instance))
  52. {
  53. EditorApplication.delayCall += () =>
  54. {
  55. Selection.activeObject = instance.gameObject;
  56. InternalEditorUtility.SetIsInspectorExpanded(instance, true);
  57. };
  58. break;
  59. }
  60. }
  61. };
  62. }
  63. /************************************************************************************************************************/
  64. /// <summary>Custom editor for <see cref="SampleReadMe"/>.</summary>
  65. [CustomEditor(typeof(SampleReadMe))]
  66. public class Editor : UnityEditor.Editor
  67. {
  68. /************************************************************************************************************************/
  69. private static GUIStyle _HeaderStyle;
  70. private static GUIStyle _BodyStyle;
  71. private static GUIStyle _FooterStyle;
  72. private static void InitializeStyles()
  73. {
  74. if (_HeaderStyle != null)
  75. return;
  76. GUIStyle label = GUI.skin.label;
  77. _HeaderStyle = new(label)
  78. {
  79. stretchWidth = false,
  80. };
  81. _HeaderStyle.fontSize *= 2;
  82. _HeaderStyle.normal.textColor = _HeaderStyle.hover.textColor =
  83. new Color32(0x00, 0x78, 0xDA, 0xFF);
  84. _BodyStyle = new(label)
  85. {
  86. richText = true,
  87. wordWrap = true,
  88. };
  89. _FooterStyle = new(label)
  90. {
  91. fontStyle = FontStyle.Italic,
  92. };
  93. _FooterStyle.fontSize = (int)(_FooterStyle.fontSize * 0.75f);
  94. }
  95. /************************************************************************************************************************/
  96. private static readonly GUIContent UrlContent = new("", "Click to copy this link to the clipboard");
  97. /// <inheritdoc/>
  98. public override void OnInspectorGUI()
  99. {
  100. InitializeStyles();
  101. GUILayout.BeginVertical();
  102. SampleReadMe target = (SampleReadMe)this.target;
  103. Scene scene = target.gameObject.scene;
  104. if (!scene.IsValid())
  105. {
  106. GUILayout.Label("This component only works inside scenes.", _BodyStyle);
  107. return;
  108. }
  109. string url = GetDocumentationURL(scene.path);
  110. // Header.
  111. string number = GetSampleNumber(scene);
  112. if (!string.IsNullOrEmpty(number))
  113. GUILayout.Label(number, _FooterStyle);
  114. GUILayout.Label(scene.name, _HeaderStyle);
  115. Rect headerArea = GUILayoutUtility.GetLastRect();
  116. headerArea.y += headerArea.height;
  117. headerArea.height *= 0.05f;
  118. EditorGUI.DrawRect(headerArea, _HeaderStyle.normal.textColor);
  119. // URL.
  120. UrlContent.text = url;
  121. if (GUILayout.Button(UrlContent, _FooterStyle))
  122. {
  123. GUIUtility.systemCopyBuffer = url;
  124. Debug.Log($"Copied '{url}' to the clipboard.");
  125. }
  126. Rect urlArea = GUILayoutUtility.GetLastRect();
  127. EditorGUIUtility.AddCursorRect(urlArea, MouseCursor.Text);
  128. GUILayout.Space(_BodyStyle.fontSize);
  129. // Body.
  130. if (!string.IsNullOrEmpty(target._Text))
  131. {
  132. GUILayout.Label(target._Text, _BodyStyle);
  133. GUILayout.Space(_BodyStyle.fontSize);
  134. }
  135. // Footer.
  136. GUILayout.Label("Click here to open the detailed online documentation.", _FooterStyle);
  137. GUILayout.EndVertical();
  138. // Click to open URL.
  139. Rect area = GUILayoutUtility.GetLastRect();
  140. EditorGUIUtility.AddCursorRect(area, MouseCursor.Link);
  141. Event currentEvent = Event.current;
  142. if (currentEvent.type == EventType.MouseUp &&
  143. area.Contains(currentEvent.mousePosition))
  144. Application.OpenURL(url);
  145. //base.OnInspectorGUI();// Uncomment to allow editing.
  146. }
  147. /************************************************************************************************************************/
  148. [NonSerialized]
  149. private string _SampleNumber;
  150. private string GetSampleNumber(Scene scene)
  151. {
  152. if (_SampleNumber is not null)
  153. return _SampleNumber;
  154. try
  155. {
  156. string directory = Path.GetDirectoryName(scene.path);
  157. string name = Path.GetFileName(directory);
  158. int space = name.IndexOf(' ');
  159. _SampleNumber = name[..space];
  160. directory = Path.GetDirectoryName(directory);
  161. name = Path.GetFileName(directory);
  162. space = name.IndexOf(' ');
  163. _SampleNumber = $"{name[..space]}-{_SampleNumber}";
  164. }
  165. catch (Exception exception)
  166. {
  167. _SampleNumber = "";
  168. _DocumentationURL = $"Failed to get Sample Number for {scene.path}: {exception}";
  169. }
  170. return _SampleNumber;
  171. }
  172. /************************************************************************************************************************/
  173. [NonSerialized]
  174. private string _DocumentationURL;
  175. private string GetDocumentationURL(string scenePath)
  176. {
  177. if (_DocumentationURL is not null)
  178. return _DocumentationURL;
  179. try
  180. {
  181. scenePath = Path.GetDirectoryName(scenePath);
  182. string urlPath = Path.Combine(scenePath, "Documentation.URL");
  183. string urlText = File.ReadAllText(urlPath);
  184. const string Prefix = "URL=";
  185. int start = urlText.IndexOf(Prefix) + Prefix.Length;
  186. int end = urlText.IndexOf('\n', start);
  187. _DocumentationURL = urlText[start..end];
  188. }
  189. catch (Exception exception)
  190. {
  191. _DocumentationURL = $"Failed to get Documentation URL for {scenePath}: {exception}";
  192. }
  193. return _DocumentationURL;
  194. }
  195. /************************************************************************************************************************/
  196. }
  197. /************************************************************************************************************************/
  198. #endif
  199. /************************************************************************************************************************/
  200. #region Unity Modules
  201. /************************************************************************************************************************/
  202. /// <summary>Returns an error message about a missing Unity module.</summary>
  203. [HideInCallstack]
  204. public static void LogMissingModuleError(string name, string url, Object context)
  205. => Debug.LogError(
  206. $"{context.GetType().Name} requires Unity's '{name}'" +
  207. $" module to be enabled in the Package Manager. {url}",
  208. context);
  209. #if !UNITY_AUDIO
  210. /// <summary>An error message about the 'Audio' module being missing.</summary>
  211. [HideInCallstack]
  212. public static void LogMissingAudioModuleError(Object context)
  213. => LogMissingModuleError(
  214. "Audio",
  215. "https://docs.unity3d.com/ScriptReference/UnityEngine.AudioModule.html",
  216. context);
  217. #endif
  218. #if !UNITY_JSON_SERIALIZE
  219. /// <summary>An error message about the 'JSON Serialize' module being missing.</summary>
  220. [HideInCallstack]
  221. public static void LogMissingJsonSerializeModuleError(Object context)
  222. => LogMissingModuleError(
  223. "JSON Serialize",
  224. "https://docs.unity3d.com/ScriptReference/UnityEngine.JSONSerializeModule.html",
  225. context);
  226. #endif
  227. #if !UNITY_PHYSICS_3D
  228. /// <summary>An error message about the 'Physics' module being missing.</summary>
  229. [HideInCallstack]
  230. public static void LogMissingPhysics3DModuleError(Object context)
  231. => LogMissingModuleError(
  232. "Physics",
  233. "https://docs.unity3d.com/ScriptReference/UnityEngine.PhysicsModule.html",
  234. context);
  235. #endif
  236. #if !UNITY_UGUI
  237. /// <summary>An error message about the 'Unity UI' module being missing.</summary>
  238. [HideInCallstack]
  239. public static void LogMissingUnityUIModuleError(Object context)
  240. => LogMissingModuleError(
  241. "Unity UGUI",
  242. "https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/index.html",
  243. context);
  244. #endif
  245. /************************************************************************************************************************/
  246. #endregion
  247. /************************************************************************************************************************/
  248. }
  249. }
  250. #endif