Ei kuvausta
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MenuOptions.cs 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. using System;
  2. using UnityEditor.SceneManagement;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. using UnityEngine.UI;
  6. namespace UnityEditor.UI
  7. {
  8. /// <summary>
  9. /// This script adds the UI menu options to the Unity Editor.
  10. /// </summary>
  11. static internal class MenuOptions
  12. {
  13. enum MenuOptionsPriorityOrder {
  14. // 2000 - Text (TMP)
  15. Image = 2001,
  16. RawImage = 2002,
  17. Panel = 2003,
  18. // 2020 - Button (TMP)
  19. Toggle = 2021,
  20. // 2022 - Dropdown (TMP)
  21. // 2023 - Input Field (TMP)
  22. Slider = 2024,
  23. Scrollbar = 2025,
  24. ScrollView = 2026,
  25. Canvas = 2060,
  26. EventSystem = 2061,
  27. Text = 2080,
  28. Button = 2081,
  29. Dropdown = 2082,
  30. InputField = 2083,
  31. };
  32. private const string kUILayerName = "UI";
  33. private const string kStandardSpritePath = "UI/Skin/UISprite.psd";
  34. private const string kBackgroundSpritePath = "UI/Skin/Background.psd";
  35. private const string kInputFieldBackgroundPath = "UI/Skin/InputFieldBackground.psd";
  36. private const string kKnobPath = "UI/Skin/Knob.psd";
  37. private const string kCheckmarkPath = "UI/Skin/Checkmark.psd";
  38. private const string kDropdownArrowPath = "UI/Skin/DropdownArrow.psd";
  39. private const string kMaskPath = "UI/Skin/UIMask.psd";
  40. static private DefaultControls.Resources s_StandardResources;
  41. static private DefaultControls.Resources GetStandardResources()
  42. {
  43. if (s_StandardResources.standard == null)
  44. {
  45. s_StandardResources.standard = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath);
  46. s_StandardResources.background = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpritePath);
  47. s_StandardResources.inputField = AssetDatabase.GetBuiltinExtraResource<Sprite>(kInputFieldBackgroundPath);
  48. s_StandardResources.knob = AssetDatabase.GetBuiltinExtraResource<Sprite>(kKnobPath);
  49. s_StandardResources.checkmark = AssetDatabase.GetBuiltinExtraResource<Sprite>(kCheckmarkPath);
  50. s_StandardResources.dropdown = AssetDatabase.GetBuiltinExtraResource<Sprite>(kDropdownArrowPath);
  51. s_StandardResources.mask = AssetDatabase.GetBuiltinExtraResource<Sprite>(kMaskPath);
  52. }
  53. return s_StandardResources;
  54. }
  55. private class DefaultEditorFactory : DefaultControls.IFactoryControls
  56. {
  57. public static DefaultEditorFactory Default = new DefaultEditorFactory();
  58. public GameObject CreateGameObject(string name, params Type[] components)
  59. {
  60. return ObjectFactory.CreateGameObject(name, components);
  61. }
  62. }
  63. private class FactorySwapToEditor : IDisposable
  64. {
  65. DefaultControls.IFactoryControls factory;
  66. public FactorySwapToEditor()
  67. {
  68. factory = DefaultControls.factory;
  69. DefaultControls.factory = DefaultEditorFactory.Default;
  70. }
  71. public void Dispose()
  72. {
  73. DefaultControls.factory = factory;
  74. }
  75. }
  76. private static void SetPositionVisibleinSceneView(RectTransform canvasRTransform, RectTransform itemTransform)
  77. {
  78. SceneView sceneView = SceneView.lastActiveSceneView;
  79. // Couldn't find a SceneView. Don't set position.
  80. if (sceneView == null || sceneView.camera == null)
  81. return;
  82. // Create world space Plane from canvas position.
  83. Vector2 localPlanePosition;
  84. Camera camera = sceneView.camera;
  85. Vector3 position = Vector3.zero;
  86. if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRTransform, new Vector2(camera.pixelWidth / 2, camera.pixelHeight / 2), camera, out localPlanePosition))
  87. {
  88. // Adjust for canvas pivot
  89. localPlanePosition.x = localPlanePosition.x + canvasRTransform.sizeDelta.x * canvasRTransform.pivot.x;
  90. localPlanePosition.y = localPlanePosition.y + canvasRTransform.sizeDelta.y * canvasRTransform.pivot.y;
  91. localPlanePosition.x = Mathf.Clamp(localPlanePosition.x, 0, canvasRTransform.sizeDelta.x);
  92. localPlanePosition.y = Mathf.Clamp(localPlanePosition.y, 0, canvasRTransform.sizeDelta.y);
  93. // Adjust for anchoring
  94. position.x = localPlanePosition.x - canvasRTransform.sizeDelta.x * itemTransform.anchorMin.x;
  95. position.y = localPlanePosition.y - canvasRTransform.sizeDelta.y * itemTransform.anchorMin.y;
  96. Vector3 minLocalPosition;
  97. minLocalPosition.x = canvasRTransform.sizeDelta.x * (0 - canvasRTransform.pivot.x) + itemTransform.sizeDelta.x * itemTransform.pivot.x;
  98. minLocalPosition.y = canvasRTransform.sizeDelta.y * (0 - canvasRTransform.pivot.y) + itemTransform.sizeDelta.y * itemTransform.pivot.y;
  99. Vector3 maxLocalPosition;
  100. maxLocalPosition.x = canvasRTransform.sizeDelta.x * (1 - canvasRTransform.pivot.x) - itemTransform.sizeDelta.x * itemTransform.pivot.x;
  101. maxLocalPosition.y = canvasRTransform.sizeDelta.y * (1 - canvasRTransform.pivot.y) - itemTransform.sizeDelta.y * itemTransform.pivot.y;
  102. position.x = Mathf.Clamp(position.x, minLocalPosition.x, maxLocalPosition.x);
  103. position.y = Mathf.Clamp(position.y, minLocalPosition.y, maxLocalPosition.y);
  104. }
  105. itemTransform.anchoredPosition = position;
  106. itemTransform.localRotation = Quaternion.identity;
  107. itemTransform.localScale = Vector3.one;
  108. }
  109. private static void PlaceUIElementRoot(GameObject element, MenuCommand menuCommand)
  110. {
  111. GameObject parent = menuCommand.context as GameObject;
  112. bool explicitParentChoice = true;
  113. if (parent == null)
  114. {
  115. parent = GetOrCreateCanvasGameObject();
  116. explicitParentChoice = false;
  117. // If in Prefab Mode, Canvas has to be part of Prefab contents,
  118. // otherwise use Prefab root instead.
  119. PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
  120. if (prefabStage != null && !prefabStage.IsPartOfPrefabContents(parent))
  121. parent = prefabStage.prefabContentsRoot;
  122. }
  123. if (parent.GetComponentsInParent<Canvas>(true).Length == 0)
  124. {
  125. // Create canvas under context GameObject,
  126. // and make that be the parent which UI element is added under.
  127. GameObject canvas = MenuOptions.CreateNewUI();
  128. Undo.SetTransformParent(canvas.transform, parent.transform, "");
  129. parent = canvas;
  130. }
  131. GameObjectUtility.EnsureUniqueNameForSibling(element);
  132. SetParentAndAlign(element, parent);
  133. if (!explicitParentChoice) // not a context click, so center in sceneview
  134. SetPositionVisibleinSceneView(parent.GetComponent<RectTransform>(), element.GetComponent<RectTransform>());
  135. // This call ensure any change made to created Objects after they where registered will be part of the Undo.
  136. Undo.RegisterFullObjectHierarchyUndo(parent == null ? element : parent, "");
  137. // We have to fix up the undo name since the name of the object was only known after reparenting it.
  138. Undo.SetCurrentGroupName("Create " + element.name);
  139. Selection.activeGameObject = element;
  140. }
  141. private static void SetParentAndAlign(GameObject child, GameObject parent)
  142. {
  143. if (parent == null)
  144. return;
  145. Undo.SetTransformParent(child.transform, parent.transform, "");
  146. RectTransform rectTransform = child.transform as RectTransform;
  147. if (rectTransform)
  148. {
  149. rectTransform.anchoredPosition = Vector2.zero;
  150. Vector3 localPosition = rectTransform.localPosition;
  151. localPosition.z = 0;
  152. rectTransform.localPosition = localPosition;
  153. }
  154. else
  155. {
  156. child.transform.localPosition = Vector3.zero;
  157. }
  158. child.transform.localRotation = Quaternion.identity;
  159. child.transform.localScale = Vector3.one;
  160. SetLayerRecursively(child, parent.layer);
  161. }
  162. private static void SetLayerRecursively(GameObject go, int layer)
  163. {
  164. go.layer = layer;
  165. Transform t = go.transform;
  166. for (int i = 0; i < t.childCount; i++)
  167. SetLayerRecursively(t.GetChild(i).gameObject, layer);
  168. }
  169. // Graphic elements
  170. [MenuItem("GameObject/UI/Image", false, (int)MenuOptionsPriorityOrder.Image)]
  171. static public void AddImage(MenuCommand menuCommand)
  172. {
  173. GameObject go;
  174. using (new FactorySwapToEditor())
  175. go = DefaultControls.CreateImage(GetStandardResources());
  176. PlaceUIElementRoot(go, menuCommand);
  177. }
  178. [MenuItem("GameObject/UI/Raw Image", false, (int)MenuOptionsPriorityOrder.RawImage)]
  179. static public void AddRawImage(MenuCommand menuCommand)
  180. {
  181. GameObject go;
  182. using (new FactorySwapToEditor())
  183. go = DefaultControls.CreateRawImage(GetStandardResources());
  184. PlaceUIElementRoot(go, menuCommand);
  185. }
  186. [MenuItem("GameObject/UI/Panel", false, (int)MenuOptionsPriorityOrder.Panel)]
  187. static public void AddPanel(MenuCommand menuCommand)
  188. {
  189. GameObject go;
  190. using (new FactorySwapToEditor())
  191. go = DefaultControls.CreatePanel(GetStandardResources());
  192. PlaceUIElementRoot(go, menuCommand);
  193. // Panel is special, we need to ensure there's no padding after repositioning.
  194. RectTransform rect = go.GetComponent<RectTransform>();
  195. rect.anchoredPosition = Vector2.zero;
  196. rect.sizeDelta = Vector2.zero;
  197. }
  198. // Controls
  199. // Toggle is a control you just click on.
  200. [MenuItem("GameObject/UI/Toggle", false, (int)MenuOptionsPriorityOrder.Toggle)]
  201. static public void AddToggle(MenuCommand menuCommand)
  202. {
  203. GameObject go;
  204. using (new FactorySwapToEditor())
  205. go = DefaultControls.CreateToggle(GetStandardResources());
  206. PlaceUIElementRoot(go, menuCommand);
  207. }
  208. // Slider and Scrollbar modify a number
  209. [MenuItem("GameObject/UI/Slider", false, (int)MenuOptionsPriorityOrder.Slider)]
  210. static public void AddSlider(MenuCommand menuCommand)
  211. {
  212. GameObject go;
  213. using (new FactorySwapToEditor())
  214. go = DefaultControls.CreateSlider(GetStandardResources());
  215. PlaceUIElementRoot(go, menuCommand);
  216. }
  217. [MenuItem("GameObject/UI/Scrollbar", false, (int)MenuOptionsPriorityOrder.Scrollbar)]
  218. static public void AddScrollbar(MenuCommand menuCommand)
  219. {
  220. GameObject go;
  221. using (new FactorySwapToEditor())
  222. go = DefaultControls.CreateScrollbar(GetStandardResources());
  223. PlaceUIElementRoot(go, menuCommand);
  224. }
  225. [MenuItem("GameObject/UI/Scroll View", false, (int)MenuOptionsPriorityOrder.ScrollView)]
  226. static public void AddScrollView(MenuCommand menuCommand)
  227. {
  228. GameObject go;
  229. using (new FactorySwapToEditor())
  230. go = DefaultControls.CreateScrollView(GetStandardResources());
  231. PlaceUIElementRoot(go, menuCommand);
  232. }
  233. // Containers
  234. [MenuItem("GameObject/UI/Canvas", false, (int)MenuOptionsPriorityOrder.Canvas)]
  235. static public void AddCanvas(MenuCommand menuCommand)
  236. {
  237. var go = CreateNewUI();
  238. SetParentAndAlign(go, menuCommand.context as GameObject);
  239. if (go.transform.parent as RectTransform)
  240. {
  241. RectTransform rect = go.transform as RectTransform;
  242. rect.anchorMin = Vector2.zero;
  243. rect.anchorMax = Vector2.one;
  244. rect.anchoredPosition = Vector2.zero;
  245. rect.sizeDelta = Vector2.zero;
  246. }
  247. Selection.activeGameObject = go;
  248. }
  249. // Legacy Elements
  250. [MenuItem("GameObject/UI/Legacy/Text", false, (int)MenuOptionsPriorityOrder.Text)]
  251. static public void AddText(MenuCommand menuCommand)
  252. {
  253. GameObject go;
  254. using (new FactorySwapToEditor())
  255. go = DefaultControls.CreateText(GetStandardResources());
  256. PlaceUIElementRoot(go, menuCommand);
  257. }
  258. [MenuItem("GameObject/UI/Legacy/Button", false, (int)MenuOptionsPriorityOrder.Button)]
  259. static public void AddButton(MenuCommand menuCommand)
  260. {
  261. GameObject go;
  262. using (new FactorySwapToEditor())
  263. go = DefaultControls.CreateButton(GetStandardResources());
  264. PlaceUIElementRoot(go, menuCommand);
  265. }
  266. [MenuItem("GameObject/UI/Legacy/Dropdown", false, (int)MenuOptionsPriorityOrder.Dropdown)]
  267. static public void AddDropdown(MenuCommand menuCommand)
  268. {
  269. GameObject go;
  270. using (new FactorySwapToEditor())
  271. go = DefaultControls.CreateDropdown(GetStandardResources());
  272. PlaceUIElementRoot(go, menuCommand);
  273. }
  274. [MenuItem("GameObject/UI/Legacy/Input Field", false, (int)MenuOptionsPriorityOrder.InputField)]
  275. public static void AddInputField(MenuCommand menuCommand)
  276. {
  277. GameObject go;
  278. using (new FactorySwapToEditor())
  279. go = DefaultControls.CreateInputField(GetStandardResources());
  280. PlaceUIElementRoot(go, menuCommand);
  281. }
  282. // Helper methods
  283. static public GameObject CreateNewUI()
  284. {
  285. // Root for the UI
  286. var root = ObjectFactory.CreateGameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
  287. root.layer = LayerMask.NameToLayer(kUILayerName);
  288. Canvas canvas = root.GetComponent<Canvas>();
  289. canvas.renderMode = RenderMode.ScreenSpaceOverlay;
  290. // Works for all stages.
  291. StageUtility.PlaceGameObjectInCurrentStage(root);
  292. bool customScene = false;
  293. PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
  294. if (prefabStage != null)
  295. {
  296. Undo.SetTransformParent(root.transform, prefabStage.prefabContentsRoot.transform, "");
  297. customScene = true;
  298. }
  299. Undo.SetCurrentGroupName("Create " + root.name);
  300. // If there is no event system add one...
  301. // No need to place event system in custom scene as these are temporary anyway.
  302. // It can be argued for or against placing it in the user scenes,
  303. // but let's not modify scene user is not currently looking at.
  304. if (!customScene)
  305. CreateEventSystem(false);
  306. return root;
  307. }
  308. [MenuItem("GameObject/UI/Event System", false, (int)MenuOptionsPriorityOrder.EventSystem)]
  309. public static void CreateEventSystem(MenuCommand menuCommand)
  310. {
  311. GameObject parent = menuCommand.context as GameObject;
  312. CreateEventSystem(true, parent);
  313. }
  314. private static void CreateEventSystem(bool select)
  315. {
  316. CreateEventSystem(select, null);
  317. }
  318. private static void CreateEventSystem(bool select, GameObject parent)
  319. {
  320. StageHandle stage = parent == null ? StageUtility.GetCurrentStageHandle() : StageUtility.GetStageHandle(parent);
  321. var esys = stage.FindComponentOfType<EventSystem>();
  322. if (esys == null)
  323. {
  324. var eventSystem = ObjectFactory.CreateGameObject("EventSystem");
  325. if (parent == null)
  326. StageUtility.PlaceGameObjectInCurrentStage(eventSystem);
  327. else
  328. SetParentAndAlign(eventSystem, parent);
  329. esys = ObjectFactory.AddComponent<EventSystem>(eventSystem);
  330. ObjectFactory.AddComponent<StandaloneInputModule>(eventSystem);
  331. Undo.RegisterCreatedObjectUndo(eventSystem, "Create " + eventSystem.name);
  332. }
  333. if (select && esys != null)
  334. {
  335. Selection.activeGameObject = esys.gameObject;
  336. }
  337. }
  338. // Helper function that returns a Canvas GameObject; preferably a parent of the selection, or other existing Canvas.
  339. static public GameObject GetOrCreateCanvasGameObject()
  340. {
  341. GameObject selectedGo = Selection.activeGameObject;
  342. // Try to find a gameobject that is the selected GO or one if its parents.
  343. Canvas canvas = (selectedGo != null) ? selectedGo.GetComponentInParent<Canvas>() : null;
  344. if (IsValidCanvas(canvas))
  345. return canvas.gameObject;
  346. // No canvas in selection or its parents? Then use any valid canvas.
  347. // We have to find all loaded Canvases, not just the ones in main scenes.
  348. Canvas[] canvasArray = StageUtility.GetCurrentStageHandle().FindComponentsOfType<Canvas>();
  349. for (int i = 0; i < canvasArray.Length; i++)
  350. if (IsValidCanvas(canvasArray[i]))
  351. return canvasArray[i].gameObject;
  352. // No canvas in the scene at all? Then create a new one.
  353. return MenuOptions.CreateNewUI();
  354. }
  355. static bool IsValidCanvas(Canvas canvas)
  356. {
  357. if (canvas == null || !canvas.gameObject.activeInHierarchy)
  358. return false;
  359. // It's important that the non-editable canvas from a prefab scene won't be rejected,
  360. // but canvases not visible in the Hierarchy at all do. Don't check for HideAndDontSave.
  361. if (EditorUtility.IsPersistent(canvas) || (canvas.hideFlags & HideFlags.HideInHierarchy) != 0)
  362. return false;
  363. return StageUtility.GetStageHandle(canvas.gameObject) == StageUtility.GetCurrentStageHandle();
  364. }
  365. }
  366. }