TMP_Dropdown.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using UnityEngine.Events;
  7. using UnityEngine.EventSystems;
  8. using UnityEngine.UI.CoroutineTween;
  9. namespace TMPro
  10. {
  11. [AddComponentMenu("UI/Dropdown - TextMeshPro", 35)]
  12. [RequireComponent(typeof(RectTransform))]
  13. /// <summary>
  14. /// A standard dropdown that presents a list of options when clicked, of which one can be chosen.
  15. /// </summary>
  16. /// <remarks>
  17. /// The dropdown component is a Selectable. When an option is chosen, the label and/or image of the control changes to show the chosen option.
  18. ///
  19. /// When a dropdown event occurs a callback is sent to any registered listeners of onValueChanged.
  20. /// </remarks>
  21. public class TMP_Dropdown : Selectable, IPointerClickHandler, ISubmitHandler, ICancelHandler
  22. {
  23. protected internal class DropdownItem : MonoBehaviour, IPointerEnterHandler, ICancelHandler
  24. {
  25. [SerializeField]
  26. private TMP_Text m_Text;
  27. [SerializeField]
  28. private Image m_Image;
  29. [SerializeField]
  30. private RectTransform m_RectTransform;
  31. [SerializeField]
  32. private Toggle m_Toggle;
  33. public TMP_Text text { get { return m_Text; } set { m_Text = value; } }
  34. public Image image { get { return m_Image; } set { m_Image = value; } }
  35. public RectTransform rectTransform { get { return m_RectTransform; } set { m_RectTransform = value; } }
  36. public Toggle toggle { get { return m_Toggle; } set { m_Toggle = value; } }
  37. public virtual void OnPointerEnter(PointerEventData eventData)
  38. {
  39. EventSystem.current.SetSelectedGameObject(gameObject);
  40. }
  41. public virtual void OnCancel(BaseEventData eventData)
  42. {
  43. TMP_Dropdown dropdown = GetComponentInParent<TMP_Dropdown>();
  44. if (dropdown)
  45. dropdown.Hide();
  46. }
  47. }
  48. [Serializable]
  49. /// <summary>
  50. /// Class to store the text and/or image of a single option in the dropdown list.
  51. /// </summary>
  52. public class OptionData
  53. {
  54. [SerializeField]
  55. private string m_Text;
  56. [SerializeField]
  57. private Sprite m_Image;
  58. /// <summary>
  59. /// The text associated with the option.
  60. /// </summary>
  61. public string text { get { return m_Text; } set { m_Text = value; } }
  62. /// <summary>
  63. /// The image associated with the option.
  64. /// </summary>
  65. public Sprite image { get { return m_Image; } set { m_Image = value; } }
  66. public OptionData() { }
  67. public OptionData(string text)
  68. {
  69. this.text = text;
  70. }
  71. public OptionData(Sprite image)
  72. {
  73. this.image = image;
  74. }
  75. /// <summary>
  76. /// Create an object representing a single option for the dropdown list.
  77. /// </summary>
  78. /// <param name="text">Optional text for the option.</param>
  79. /// <param name="image">Optional image for the option.</param>
  80. public OptionData(string text, Sprite image)
  81. {
  82. this.text = text;
  83. this.image = image;
  84. }
  85. }
  86. [Serializable]
  87. /// <summary>
  88. /// Class used internally to store the list of options for the dropdown list.
  89. /// </summary>
  90. /// <remarks>
  91. /// The usage of this class is not exposed in the runtime API. It's only relevant for the PropertyDrawer drawing the list of options.
  92. /// </remarks>
  93. public class OptionDataList
  94. {
  95. [SerializeField]
  96. private List<OptionData> m_Options;
  97. /// <summary>
  98. /// The list of options for the dropdown list.
  99. /// </summary>
  100. public List<OptionData> options { get { return m_Options; } set { m_Options = value; } }
  101. public OptionDataList()
  102. {
  103. options = new List<OptionData>();
  104. }
  105. }
  106. [Serializable]
  107. /// <summary>
  108. /// UnityEvent callback for when a dropdown current option is changed.
  109. /// </summary>
  110. public class DropdownEvent : UnityEvent<int> { }
  111. // Template used to create the dropdown.
  112. [SerializeField]
  113. private RectTransform m_Template;
  114. /// <summary>
  115. /// The Rect Transform of the template for the dropdown list.
  116. /// </summary>
  117. public RectTransform template { get { return m_Template; } set { m_Template = value; RefreshShownValue(); } }
  118. // Text to be used as a caption for the current value. It's not required, but it's kept here for convenience.
  119. [SerializeField]
  120. private TMP_Text m_CaptionText;
  121. /// <summary>
  122. /// The Text component to hold the text of the currently selected option.
  123. /// </summary>
  124. public TMP_Text captionText { get { return m_CaptionText; } set { m_CaptionText = value; RefreshShownValue(); } }
  125. [SerializeField]
  126. private Image m_CaptionImage;
  127. /// <summary>
  128. /// The Image component to hold the image of the currently selected option.
  129. /// </summary>
  130. public Image captionImage { get { return m_CaptionImage; } set { m_CaptionImage = value; RefreshShownValue(); } }
  131. [Space]
  132. [SerializeField]
  133. private TMP_Text m_ItemText;
  134. /// <summary>
  135. /// The Text component to hold the text of the item.
  136. /// </summary>
  137. public TMP_Text itemText { get { return m_ItemText; } set { m_ItemText = value; RefreshShownValue(); } }
  138. [SerializeField]
  139. private Image m_ItemImage;
  140. /// <summary>
  141. /// The Image component to hold the image of the item
  142. /// </summary>
  143. public Image itemImage { get { return m_ItemImage; } set { m_ItemImage = value; RefreshShownValue(); } }
  144. [Space]
  145. [SerializeField]
  146. private int m_Value;
  147. [Space]
  148. // Items that will be visible when the dropdown is shown.
  149. // We box this into its own class so we can use a Property Drawer for it.
  150. [SerializeField]
  151. private OptionDataList m_Options = new OptionDataList();
  152. /// <summary>
  153. /// The list of possible options. A text string and an image can be specified for each option.
  154. /// </summary>
  155. /// <remarks>
  156. /// This is the list of options within the Dropdown. Each option contains Text and/or image data that you can specify using UI.Dropdown.OptionData before adding to the Dropdown list.
  157. /// This also unlocks the ability to edit the Dropdown, including the insertion, removal, and finding of options, as well as other useful tools
  158. /// </remarks>
  159. /// /// <example>
  160. /// <code>
  161. /// //Create a new Dropdown GameObject by going to the Hierarchy and clicking Create>UI>Dropdown - TextMeshPro. Attach this script to the Dropdown GameObject.
  162. ///
  163. /// using UnityEngine;
  164. /// using UnityEngine.UI;
  165. /// using System.Collections.Generic;
  166. /// using TMPro;
  167. ///
  168. /// public class Example : MonoBehaviour
  169. /// {
  170. /// //Use these for adding options to the Dropdown List
  171. /// TMP_Dropdown.OptionData m_NewData, m_NewData2;
  172. /// //The list of messages for the Dropdown
  173. /// List<TMP_Dropdown.OptionData> m_Messages = new List<TMP_Dropdown.OptionData>();
  174. ///
  175. ///
  176. /// //This is the Dropdown
  177. /// TMP_Dropdown m_Dropdown;
  178. /// string m_MyString;
  179. /// int m_Index;
  180. ///
  181. /// void Start()
  182. /// {
  183. /// //Fetch the Dropdown GameObject the script is attached to
  184. /// m_Dropdown = GetComponent<TMP_Dropdown>();
  185. /// //Clear the old options of the Dropdown menu
  186. /// m_Dropdown.ClearOptions();
  187. ///
  188. /// //Create a new option for the Dropdown menu which reads "Option 1" and add to messages List
  189. /// m_NewData = new TMP_Dropdown.OptionData();
  190. /// m_NewData.text = "Option 1";
  191. /// m_Messages.Add(m_NewData);
  192. ///
  193. /// //Create a new option for the Dropdown menu which reads "Option 2" and add to messages List
  194. /// m_NewData2 = new TMP_Dropdown.OptionData();
  195. /// m_NewData2.text = "Option 2";
  196. /// m_Messages.Add(m_NewData2);
  197. ///
  198. /// //Take each entry in the message List
  199. /// foreach (TMP_Dropdown.OptionData message in m_Messages)
  200. /// {
  201. /// //Add each entry to the Dropdown
  202. /// m_Dropdown.options.Add(message);
  203. /// //Make the index equal to the total number of entries
  204. /// m_Index = m_Messages.Count - 1;
  205. /// }
  206. /// }
  207. ///
  208. /// //This OnGUI function is used here for a quick demonstration. See the [[wiki:UISystem|UI Section]] for more information about setting up your own UI.
  209. /// void OnGUI()
  210. /// {
  211. /// //TextField for user to type new entry to add to Dropdown
  212. /// m_MyString = GUI.TextField(new Rect(0, 40, 100, 40), m_MyString);
  213. ///
  214. /// //Press the "Add" Button to add a new entry to the Dropdown
  215. /// if (GUI.Button(new Rect(0, 0, 100, 40), "Add"))
  216. /// {
  217. /// //Make the index the last number of entries
  218. /// m_Index = m_Messages.Count;
  219. /// //Create a temporary option
  220. /// TMP_Dropdown.OptionData temp = new TMP_Dropdown.OptionData();
  221. /// //Make the option the data from the TextField
  222. /// temp.text = m_MyString;
  223. ///
  224. /// //Update the messages list with the TextField data
  225. /// m_Messages.Add(temp);
  226. ///
  227. /// //Add the Textfield data to the Dropdown
  228. /// m_Dropdown.options.Insert(m_Index, temp);
  229. /// }
  230. ///
  231. /// //Press the "Remove" button to delete the selected option
  232. /// if (GUI.Button(new Rect(110, 0, 100, 40), "Remove"))
  233. /// {
  234. /// //Remove the current selected item from the Dropdown from the messages List
  235. /// m_Messages.RemoveAt(m_Dropdown.value);
  236. /// //Remove the current selection from the Dropdown
  237. /// m_Dropdown.options.RemoveAt(m_Dropdown.value);
  238. /// }
  239. /// }
  240. /// }
  241. /// </code>
  242. /// </example>
  243. public List<OptionData> options
  244. {
  245. get { return m_Options.options; }
  246. set { m_Options.options = value; RefreshShownValue(); }
  247. }
  248. [Space]
  249. // Notification triggered when the dropdown changes.
  250. [SerializeField]
  251. private DropdownEvent m_OnValueChanged = new DropdownEvent();
  252. /// <summary>
  253. /// A UnityEvent that is invoked when a user has clicked one of the options in the dropdown list.
  254. /// </summary>
  255. /// <remarks>
  256. /// Use this to detect when a user selects one or more options in the Dropdown. Add a listener to perform an action when this UnityEvent detects a selection by the user. See https://unity3d.com/learn/tutorials/topics/scripting/delegates for more information on delegates.
  257. /// </remarks>
  258. /// <example>
  259. /// <code>
  260. /// //Create a new Dropdown GameObject by going to the Hierarchy and clicking Create>UI>Dropdown - TextMeshPro. Attach this script to the Dropdown GameObject.
  261. /// //Set your own Text in the Inspector window
  262. ///
  263. /// using UnityEngine;
  264. /// using UnityEngine.UI;
  265. /// using TMPro;
  266. ///
  267. /// public class Example : MonoBehaviour
  268. /// {
  269. /// TMP_Dropdown m_Dropdown;
  270. /// public Text m_Text;
  271. ///
  272. /// void Start()
  273. /// {
  274. /// //Fetch the Dropdown GameObject
  275. /// m_Dropdown = GetComponent<TMP_Dropdown>();
  276. /// //Add listener for when the value of the Dropdown changes, to take action
  277. /// m_Dropdown.onValueChanged.AddListener(delegate {
  278. /// DropdownValueChanged(m_Dropdown);
  279. /// });
  280. ///
  281. /// //Initialize the Text to say the first value of the Dropdown
  282. /// m_Text.text = "First Value : " + m_Dropdown.value;
  283. /// }
  284. ///
  285. /// //Output the new value of the Dropdown into Text
  286. /// void DropdownValueChanged(TMP_Dropdown change)
  287. /// {
  288. /// m_Text.text = "New Value : " + change.value;
  289. /// }
  290. /// }
  291. /// </code>
  292. /// </example>
  293. public DropdownEvent onValueChanged { get { return m_OnValueChanged; } set { m_OnValueChanged = value; } }
  294. private GameObject m_Dropdown;
  295. private GameObject m_Blocker;
  296. private List<DropdownItem> m_Items = new List<DropdownItem>();
  297. private TweenRunner<FloatTween> m_AlphaTweenRunner;
  298. private bool validTemplate = false;
  299. private static OptionData s_NoOptionData = new OptionData();
  300. /// <summary>
  301. /// The Value is the index number of the current selection in the Dropdown. 0 is the first option in the Dropdown, 1 is the second, and so on.
  302. /// </summary>
  303. /// <example>
  304. /// <code>
  305. /// //Create a new Dropdown GameObject by going to the Hierarchy and clicking Create>UI>Dropdown - TextMeshPro. Attach this script to the Dropdown GameObject.
  306. /// //Set your own Text in the Inspector window
  307. ///
  308. /// using UnityEngine;
  309. /// using UnityEngine.UI;
  310. /// using TMPro;
  311. ///
  312. /// public class Example : MonoBehaviour
  313. /// {
  314. /// //Attach this script to a Dropdown GameObject
  315. /// TMP_Dropdown m_Dropdown;
  316. /// //This is the string that stores the current selection m_Text of the Dropdown
  317. /// string m_Message;
  318. /// //This Text outputs the current selection to the screen
  319. /// public Text m_Text;
  320. /// //This is the index value of the Dropdown
  321. /// int m_DropdownValue;
  322. ///
  323. /// void Start()
  324. /// {
  325. /// //Fetch the DropDown component from the GameObject
  326. /// m_Dropdown = GetComponent<TMP_Dropdown>();
  327. /// //Output the first Dropdown index value
  328. /// Debug.Log("Starting Dropdown Value : " + m_Dropdown.value);
  329. /// }
  330. ///
  331. /// void Update()
  332. /// {
  333. /// //Keep the current index of the Dropdown in a variable
  334. /// m_DropdownValue = m_Dropdown.value;
  335. /// //Change the message to say the name of the current Dropdown selection using the value
  336. /// m_Message = m_Dropdown.options[m_DropdownValue].text;
  337. /// //Change the on screen Text to reflect the current Dropdown selection
  338. /// m_Text.text = m_Message;
  339. /// }
  340. /// }
  341. /// </code>
  342. /// </example>
  343. public int value
  344. {
  345. get
  346. {
  347. return m_Value;
  348. }
  349. set
  350. {
  351. SetValue(value);
  352. }
  353. }
  354. /// <summary>
  355. /// Set index number of the current selection in the Dropdown without invoking onValueChanged callback.
  356. /// </summary>
  357. /// <param name="input">The new index for the current selection.</param>
  358. public void SetValueWithoutNotify(int input)
  359. {
  360. SetValue(input, false);
  361. }
  362. void SetValue(int value, bool sendCallback = true)
  363. {
  364. if (Application.isPlaying && (value == m_Value || options.Count == 0))
  365. return;
  366. m_Value = Mathf.Clamp(value, 0, options.Count - 1);
  367. RefreshShownValue();
  368. if (sendCallback)
  369. {
  370. // Notify all listeners
  371. UISystemProfilerApi.AddMarker("Dropdown.value", this);
  372. m_OnValueChanged.Invoke(m_Value);
  373. }
  374. }
  375. public bool IsExpanded { get { return m_Dropdown != null; } }
  376. protected TMP_Dropdown() { }
  377. protected override void Awake()
  378. {
  379. #if UNITY_EDITOR
  380. if (!Application.isPlaying)
  381. return;
  382. #endif
  383. m_AlphaTweenRunner = new TweenRunner<FloatTween>();
  384. m_AlphaTweenRunner.Init(this);
  385. if (m_CaptionImage)
  386. m_CaptionImage.enabled = (m_CaptionImage.sprite != null);
  387. if (m_Template)
  388. m_Template.gameObject.SetActive(false);
  389. }
  390. protected override void Start()
  391. {
  392. base.Start();
  393. RefreshShownValue();
  394. }
  395. #if UNITY_EDITOR
  396. protected override void OnValidate()
  397. {
  398. base.OnValidate();
  399. if (!IsActive())
  400. return;
  401. RefreshShownValue();
  402. }
  403. #endif
  404. protected override void OnDisable()
  405. {
  406. //Destroy dropdown and blocker in case user deactivates the dropdown when they click an option (case 935649)
  407. ImmediateDestroyDropdownList();
  408. if (m_Blocker != null)
  409. DestroyBlocker(m_Blocker);
  410. m_Blocker = null;
  411. }
  412. /// <summary>
  413. /// Refreshes the text and image (if available) of the currently selected option.
  414. /// </summary>
  415. /// <remarks>
  416. /// If you have modified the list of options, you should call this method afterwards to ensure that the visual state of the dropdown corresponds to the updated options.
  417. /// </remarks>
  418. public void RefreshShownValue()
  419. {
  420. OptionData data = s_NoOptionData;
  421. if (options.Count > 0)
  422. data = options[Mathf.Clamp(m_Value, 0, options.Count - 1)];
  423. if (m_CaptionText)
  424. {
  425. if (data != null && data.text != null)
  426. m_CaptionText.text = data.text;
  427. else
  428. m_CaptionText.text = "";
  429. }
  430. if (m_CaptionImage)
  431. {
  432. if (data != null)
  433. m_CaptionImage.sprite = data.image;
  434. else
  435. m_CaptionImage.sprite = null;
  436. m_CaptionImage.enabled = (m_CaptionImage.sprite != null);
  437. }
  438. }
  439. /// <summary>
  440. /// Add multiple options to the options of the Dropdown based on a list of OptionData objects.
  441. /// </summary>
  442. /// <param name="options">The list of OptionData to add.</param>
  443. /// /// <remarks>
  444. /// See AddOptions(List<string> options) for code example of usages.
  445. /// </remarks>
  446. public void AddOptions(List<OptionData> options)
  447. {
  448. this.options.AddRange(options);
  449. RefreshShownValue();
  450. }
  451. /// <summary>
  452. /// Add multiple text-only options to the options of the Dropdown based on a list of strings.
  453. /// </summary>
  454. /// <remarks>
  455. /// Add a List of string messages to the Dropdown. The Dropdown shows each member of the list as a separate option.
  456. /// </remarks>
  457. /// <param name="options">The list of text strings to add.</param>
  458. /// <example>
  459. /// <code>
  460. /// //Create a new Dropdown GameObject by going to the Hierarchy and clicking Create>UI>Dropdown - TextMeshPro. Attach this script to the Dropdown GameObject.
  461. ///
  462. /// using System.Collections.Generic;
  463. /// using UnityEngine;
  464. /// using UnityEngine.UI;
  465. /// using TMPro;
  466. ///
  467. /// public class Example : MonoBehaviour
  468. /// {
  469. /// //Create a List of new Dropdown options
  470. /// List<string> m_DropOptions = new List<string> { "Option 1", "Option 2"};
  471. /// //This is the Dropdown
  472. /// TMP_Dropdown m_Dropdown;
  473. ///
  474. /// void Start()
  475. /// {
  476. /// //Fetch the Dropdown GameObject the script is attached to
  477. /// m_Dropdown = GetComponent<TMP_Dropdown>();
  478. /// //Clear the old options of the Dropdown menu
  479. /// m_Dropdown.ClearOptions();
  480. /// //Add the options created in the List above
  481. /// m_Dropdown.AddOptions(m_DropOptions);
  482. /// }
  483. /// }
  484. /// </code>
  485. /// </example>
  486. public void AddOptions(List<string> options)
  487. {
  488. for (int i = 0; i < options.Count; i++)
  489. this.options.Add(new OptionData(options[i]));
  490. RefreshShownValue();
  491. }
  492. /// <summary>
  493. /// Add multiple image-only options to the options of the Dropdown based on a list of Sprites.
  494. /// </summary>
  495. /// <param name="options">The list of Sprites to add.</param>
  496. /// <remarks>
  497. /// See AddOptions(List<string> options) for code example of usages.
  498. /// </remarks>
  499. public void AddOptions(List<Sprite> options)
  500. {
  501. for (int i = 0; i < options.Count; i++)
  502. this.options.Add(new OptionData(options[i]));
  503. RefreshShownValue();
  504. }
  505. /// <summary>
  506. /// Clear the list of options in the Dropdown.
  507. /// </summary>
  508. public void ClearOptions()
  509. {
  510. options.Clear();
  511. m_Value = 0;
  512. RefreshShownValue();
  513. }
  514. private void SetupTemplate()
  515. {
  516. validTemplate = false;
  517. if (!m_Template)
  518. {
  519. Debug.LogError("The dropdown template is not assigned. The template needs to be assigned and must have a child GameObject with a Toggle component serving as the item.", this);
  520. return;
  521. }
  522. GameObject templateGo = m_Template.gameObject;
  523. templateGo.SetActive(true);
  524. Toggle itemToggle = m_Template.GetComponentInChildren<Toggle>();
  525. validTemplate = true;
  526. if (!itemToggle || itemToggle.transform == template)
  527. {
  528. validTemplate = false;
  529. Debug.LogError("The dropdown template is not valid. The template must have a child GameObject with a Toggle component serving as the item.", template);
  530. }
  531. else if (!(itemToggle.transform.parent is RectTransform))
  532. {
  533. validTemplate = false;
  534. Debug.LogError("The dropdown template is not valid. The child GameObject with a Toggle component (the item) must have a RectTransform on its parent.", template);
  535. }
  536. else if (itemText != null && !itemText.transform.IsChildOf(itemToggle.transform))
  537. {
  538. validTemplate = false;
  539. Debug.LogError("The dropdown template is not valid. The Item Text must be on the item GameObject or children of it.", template);
  540. }
  541. else if (itemImage != null && !itemImage.transform.IsChildOf(itemToggle.transform))
  542. {
  543. validTemplate = false;
  544. Debug.LogError("The dropdown template is not valid. The Item Image must be on the item GameObject or children of it.", template);
  545. }
  546. if (!validTemplate)
  547. {
  548. templateGo.SetActive(false);
  549. return;
  550. }
  551. DropdownItem item = itemToggle.gameObject.AddComponent<DropdownItem>();
  552. item.text = m_ItemText;
  553. item.image = m_ItemImage;
  554. item.toggle = itemToggle;
  555. item.rectTransform = (RectTransform)itemToggle.transform;
  556. Canvas popupCanvas = GetOrAddComponent<Canvas>(templateGo);
  557. popupCanvas.overrideSorting = true;
  558. popupCanvas.sortingOrder = 30000;
  559. GetOrAddComponent<GraphicRaycaster>(templateGo);
  560. GetOrAddComponent<CanvasGroup>(templateGo);
  561. templateGo.SetActive(false);
  562. validTemplate = true;
  563. }
  564. private static T GetOrAddComponent<T>(GameObject go) where T : Component
  565. {
  566. T comp = go.GetComponent<T>();
  567. if (!comp)
  568. comp = go.AddComponent<T>();
  569. return comp;
  570. }
  571. /// <summary>
  572. /// Handling for when the dropdown is initially 'clicked'. Typically shows the dropdown
  573. /// </summary>
  574. /// <param name="eventData">The associated event data.</param>
  575. public virtual void OnPointerClick(PointerEventData eventData)
  576. {
  577. Show();
  578. }
  579. /// <summary>
  580. /// Handling for when the dropdown is selected and a submit event is processed. Typically shows the dropdown
  581. /// </summary>
  582. /// <param name="eventData">The associated event data.</param>
  583. public virtual void OnSubmit(BaseEventData eventData)
  584. {
  585. Show();
  586. }
  587. /// <summary>
  588. /// This will hide the dropdown list.
  589. /// </summary>
  590. /// <remarks>
  591. /// Called by a BaseInputModule when a Cancel event occurs.
  592. /// </remarks>
  593. /// <param name="eventData">The associated event data.</param>
  594. public virtual void OnCancel(BaseEventData eventData)
  595. {
  596. Hide();
  597. }
  598. /// <summary>
  599. /// Show the dropdown.
  600. ///
  601. /// Plan for dropdown scrolling to ensure dropdown is contained within screen.
  602. ///
  603. /// We assume the Canvas is the screen that the dropdown must be kept inside.
  604. /// This is always valid for screen space canvas modes.
  605. /// For world space canvases we don't know how it's used, but it could be e.g. for an in-game monitor.
  606. /// We consider it a fair constraint that the canvas must be big enough to contain dropdowns.
  607. /// </summary>
  608. public void Show()
  609. {
  610. if (!IsActive() || !IsInteractable() || m_Dropdown != null)
  611. return;
  612. // Get root Canvas.
  613. var list = TMP_ListPool<Canvas>.Get();
  614. gameObject.GetComponentsInParent(false, list);
  615. if (list.Count == 0)
  616. return;
  617. Canvas rootCanvas = list[list.Count - 1];
  618. for (int i = 0; i < list.Count; i++)
  619. {
  620. if (list[i].isRootCanvas)
  621. {
  622. rootCanvas = list[i];
  623. break;
  624. }
  625. }
  626. TMP_ListPool<Canvas>.Release(list);
  627. if (!validTemplate)
  628. {
  629. SetupTemplate();
  630. if (!validTemplate)
  631. return;
  632. }
  633. m_Template.gameObject.SetActive(true);
  634. // popupCanvas used to assume the root canvas had the default sorting Layer, next line fixes (case 958281 - [UI] Dropdown list does not copy the parent canvas layer when the panel is opened)
  635. m_Template.GetComponent<Canvas>().sortingLayerID = rootCanvas.sortingLayerID;
  636. // Instantiate the drop-down template
  637. m_Dropdown = CreateDropdownList(m_Template.gameObject);
  638. m_Dropdown.name = "Dropdown List";
  639. m_Dropdown.SetActive(true);
  640. // Make drop-down RectTransform have same values as original.
  641. RectTransform dropdownRectTransform = m_Dropdown.transform as RectTransform;
  642. dropdownRectTransform.SetParent(m_Template.transform.parent, false);
  643. // Instantiate the drop-down list items
  644. // Find the dropdown item and disable it.
  645. DropdownItem itemTemplate = m_Dropdown.GetComponentInChildren<DropdownItem>();
  646. GameObject content = itemTemplate.rectTransform.parent.gameObject;
  647. RectTransform contentRectTransform = content.transform as RectTransform;
  648. itemTemplate.rectTransform.gameObject.SetActive(true);
  649. // Get the rects of the dropdown and item
  650. Rect dropdownContentRect = contentRectTransform.rect;
  651. Rect itemTemplateRect = itemTemplate.rectTransform.rect;
  652. // Calculate the visual offset between the item's edges and the background's edges
  653. Vector2 offsetMin = itemTemplateRect.min - dropdownContentRect.min + (Vector2)itemTemplate.rectTransform.localPosition;
  654. Vector2 offsetMax = itemTemplateRect.max - dropdownContentRect.max + (Vector2)itemTemplate.rectTransform.localPosition;
  655. Vector2 itemSize = itemTemplateRect.size;
  656. m_Items.Clear();
  657. Toggle prev = null;
  658. for (int i = 0; i < options.Count; ++i)
  659. {
  660. OptionData data = options[i];
  661. DropdownItem item = AddItem(data, value == i, itemTemplate, m_Items);
  662. if (item == null)
  663. continue;
  664. // Automatically set up a toggle state change listener
  665. item.toggle.isOn = value == i;
  666. item.toggle.onValueChanged.AddListener(x => OnSelectItem(item.toggle));
  667. // Select current option
  668. if (item.toggle.isOn)
  669. item.toggle.Select();
  670. // Automatically set up explicit navigation
  671. if (prev != null)
  672. {
  673. Navigation prevNav = prev.navigation;
  674. Navigation toggleNav = item.toggle.navigation;
  675. prevNav.mode = Navigation.Mode.Explicit;
  676. toggleNav.mode = Navigation.Mode.Explicit;
  677. prevNav.selectOnDown = item.toggle;
  678. prevNav.selectOnRight = item.toggle;
  679. toggleNav.selectOnLeft = prev;
  680. toggleNav.selectOnUp = prev;
  681. prev.navigation = prevNav;
  682. item.toggle.navigation = toggleNav;
  683. }
  684. prev = item.toggle;
  685. }
  686. // Reposition all items now that all of them have been added
  687. Vector2 sizeDelta = contentRectTransform.sizeDelta;
  688. sizeDelta.y = itemSize.y * m_Items.Count + offsetMin.y - offsetMax.y;
  689. contentRectTransform.sizeDelta = sizeDelta;
  690. float extraSpace = dropdownRectTransform.rect.height - contentRectTransform.rect.height;
  691. if (extraSpace > 0)
  692. dropdownRectTransform.sizeDelta = new Vector2(dropdownRectTransform.sizeDelta.x, dropdownRectTransform.sizeDelta.y - extraSpace);
  693. // Invert anchoring and position if dropdown is partially or fully outside of canvas rect.
  694. // Typically this will have the effect of placing the dropdown above the button instead of below,
  695. // but it works as inversion regardless of initial setup.
  696. Vector3[] corners = new Vector3[4];
  697. dropdownRectTransform.GetWorldCorners(corners);
  698. RectTransform rootCanvasRectTransform = rootCanvas.transform as RectTransform;
  699. Rect rootCanvasRect = rootCanvasRectTransform.rect;
  700. for (int axis = 0; axis < 2; axis++)
  701. {
  702. bool outside = false;
  703. for (int i = 0; i < 4; i++)
  704. {
  705. Vector3 corner = rootCanvasRectTransform.InverseTransformPoint(corners[i]);
  706. if ((corner[axis] < rootCanvasRect.min[axis] && !Mathf.Approximately(corner[axis], rootCanvasRect.min[axis])) ||
  707. (corner[axis] > rootCanvasRect.max[axis] && !Mathf.Approximately(corner[axis], rootCanvasRect.max[axis])))
  708. {
  709. outside = true;
  710. break;
  711. }
  712. }
  713. if (outside)
  714. RectTransformUtility.FlipLayoutOnAxis(dropdownRectTransform, axis, false, false);
  715. }
  716. for (int i = 0; i < m_Items.Count; i++)
  717. {
  718. RectTransform itemRect = m_Items[i].rectTransform;
  719. itemRect.anchorMin = new Vector2(itemRect.anchorMin.x, 0);
  720. itemRect.anchorMax = new Vector2(itemRect.anchorMax.x, 0);
  721. itemRect.anchoredPosition = new Vector2(itemRect.anchoredPosition.x, offsetMin.y + itemSize.y * (m_Items.Count - 1 - i) + itemSize.y * itemRect.pivot.y);
  722. itemRect.sizeDelta = new Vector2(itemRect.sizeDelta.x, itemSize.y);
  723. }
  724. // Fade in the popup
  725. AlphaFadeList(0.15f, 0f, 1f);
  726. // Make drop-down template and item template inactive
  727. m_Template.gameObject.SetActive(false);
  728. itemTemplate.gameObject.SetActive(false);
  729. m_Blocker = CreateBlocker(rootCanvas);
  730. }
  731. /// <summary>
  732. /// Create a blocker that blocks clicks to other controls while the dropdown list is open.
  733. /// </summary>
  734. /// <remarks>
  735. /// Override this method to implement a different way to obtain a blocker GameObject.
  736. /// </remarks>
  737. /// <param name="rootCanvas">The root canvas the dropdown is under.</param>
  738. /// <returns>The created blocker object</returns>
  739. protected virtual GameObject CreateBlocker(Canvas rootCanvas)
  740. {
  741. // Create blocker GameObject.
  742. GameObject blocker = new GameObject("Blocker");
  743. // Setup blocker RectTransform to cover entire root canvas area.
  744. RectTransform blockerRect = blocker.AddComponent<RectTransform>();
  745. blockerRect.SetParent(rootCanvas.transform, false);
  746. blockerRect.anchorMin = Vector3.zero;
  747. blockerRect.anchorMax = Vector3.one;
  748. blockerRect.sizeDelta = Vector2.zero;
  749. // Make blocker be in separate canvas in same layer as dropdown and in layer just below it.
  750. Canvas blockerCanvas = blocker.AddComponent<Canvas>();
  751. blockerCanvas.overrideSorting = true;
  752. Canvas dropdownCanvas = m_Dropdown.GetComponent<Canvas>();
  753. blockerCanvas.sortingLayerID = dropdownCanvas.sortingLayerID;
  754. blockerCanvas.sortingOrder = dropdownCanvas.sortingOrder - 1;
  755. // Add raycaster since it's needed to block.
  756. blocker.AddComponent<GraphicRaycaster>();
  757. // Add image since it's needed to block, but make it clear.
  758. Image blockerImage = blocker.AddComponent<Image>();
  759. blockerImage.color = Color.clear;
  760. // Add button since it's needed to block, and to close the dropdown when blocking area is clicked.
  761. Button blockerButton = blocker.AddComponent<Button>();
  762. blockerButton.onClick.AddListener(Hide);
  763. return blocker;
  764. }
  765. /// <summary>
  766. /// Convenience method to explicitly destroy the previously generated blocker object
  767. /// </summary>
  768. /// <remarks>
  769. /// Override this method to implement a different way to dispose of a blocker GameObject that blocks clicks to other controls while the dropdown list is open.
  770. /// </remarks>
  771. /// <param name="blocker">The blocker object to destroy.</param>
  772. protected virtual void DestroyBlocker(GameObject blocker)
  773. {
  774. Destroy(blocker);
  775. }
  776. /// <summary>
  777. /// Create the dropdown list to be shown when the dropdown is clicked. The dropdown list should correspond to the provided template GameObject, equivalent to instantiating a copy of it.
  778. /// </summary>
  779. /// <remarks>
  780. /// Override this method to implement a different way to obtain a dropdown list GameObject.
  781. /// </remarks>
  782. /// <param name="template">The template to create the dropdown list from.</param>
  783. /// <returns>The created drop down list gameobject.</returns>
  784. protected virtual GameObject CreateDropdownList(GameObject template)
  785. {
  786. return (GameObject)Instantiate(template);
  787. }
  788. /// <summary>
  789. /// Convenience method to explicitly destroy the previously generated dropdown list
  790. /// </summary>
  791. /// <remarks>
  792. /// Override this method to implement a different way to dispose of a dropdown list GameObject.
  793. /// </remarks>
  794. /// <param name="dropdownList">The dropdown list GameObject to destroy</param>
  795. protected virtual void DestroyDropdownList(GameObject dropdownList)
  796. {
  797. Destroy(dropdownList);
  798. }
  799. /// <summary>
  800. /// Create a dropdown item based upon the item template.
  801. /// </summary>
  802. /// <remarks>
  803. /// Override this method to implement a different way to obtain an option item.
  804. /// The option item should correspond to the provided template DropdownItem and its GameObject, equivalent to instantiating a copy of it.
  805. /// </remarks>
  806. /// <param name="itemTemplate">e template to create the option item from.</param>
  807. /// <returns>The created dropdown item component</returns>
  808. protected virtual DropdownItem CreateItem(DropdownItem itemTemplate)
  809. {
  810. return (DropdownItem)Instantiate(itemTemplate);
  811. }
  812. /// <summary>
  813. /// Convenience method to explicitly destroy the previously generated Items.
  814. /// </summary>
  815. /// <remarks>
  816. /// Override this method to implement a different way to dispose of an option item.
  817. /// Likely no action needed since destroying the dropdown list destroys all contained items as well.
  818. /// </remarks>
  819. /// <param name="item">The Item to destroy.</param>
  820. protected virtual void DestroyItem(DropdownItem item) { }
  821. // Add a new drop-down list item with the specified values.
  822. private DropdownItem AddItem(OptionData data, bool selected, DropdownItem itemTemplate, List<DropdownItem> items)
  823. {
  824. // Add a new item to the dropdown.
  825. DropdownItem item = CreateItem(itemTemplate);
  826. item.rectTransform.SetParent(itemTemplate.rectTransform.parent, false);
  827. item.gameObject.SetActive(true);
  828. item.gameObject.name = "Item " + items.Count + (data.text != null ? ": " + data.text : "");
  829. if (item.toggle != null)
  830. {
  831. item.toggle.isOn = false;
  832. }
  833. // Set the item's data
  834. if (item.text)
  835. item.text.text = data.text;
  836. if (item.image)
  837. {
  838. item.image.sprite = data.image;
  839. item.image.enabled = (item.image.sprite != null);
  840. }
  841. items.Add(item);
  842. return item;
  843. }
  844. private void AlphaFadeList(float duration, float alpha)
  845. {
  846. CanvasGroup group = m_Dropdown.GetComponent<CanvasGroup>();
  847. AlphaFadeList(duration, group.alpha, alpha);
  848. }
  849. private void AlphaFadeList(float duration, float start, float end)
  850. {
  851. if (end.Equals(start))
  852. return;
  853. FloatTween tween = new FloatTween { duration = duration, startValue = start, targetValue = end };
  854. tween.AddOnChangedCallback(SetAlpha);
  855. tween.ignoreTimeScale = true;
  856. m_AlphaTweenRunner.StartTween(tween);
  857. }
  858. private void SetAlpha(float alpha)
  859. {
  860. if (!m_Dropdown)
  861. return;
  862. CanvasGroup group = m_Dropdown.GetComponent<CanvasGroup>();
  863. group.alpha = alpha;
  864. }
  865. /// <summary>
  866. /// Hide the dropdown list. I.e. close it.
  867. /// </summary>
  868. public void Hide()
  869. {
  870. if (m_Dropdown != null)
  871. {
  872. AlphaFadeList(0.15f, 0f);
  873. // User could have disabled the dropdown during the OnValueChanged call.
  874. if (IsActive())
  875. StartCoroutine(DelayedDestroyDropdownList(0.15f));
  876. }
  877. if (m_Blocker != null)
  878. DestroyBlocker(m_Blocker);
  879. m_Blocker = null;
  880. Select();
  881. }
  882. private IEnumerator DelayedDestroyDropdownList(float delay)
  883. {
  884. yield return new WaitForSecondsRealtime(delay);
  885. ImmediateDestroyDropdownList();
  886. }
  887. private void ImmediateDestroyDropdownList()
  888. {
  889. for (int i = 0; i < m_Items.Count; i++)
  890. {
  891. if (m_Items[i] != null)
  892. DestroyItem(m_Items[i]);
  893. }
  894. m_Items.Clear();
  895. if (m_Dropdown != null)
  896. DestroyDropdownList(m_Dropdown);
  897. m_Dropdown = null;
  898. }
  899. // Change the value and hide the dropdown.
  900. private void OnSelectItem(Toggle toggle)
  901. {
  902. if (!toggle.isOn)
  903. toggle.isOn = true;
  904. int selectedIndex = -1;
  905. Transform tr = toggle.transform;
  906. Transform parent = tr.parent;
  907. for (int i = 0; i < parent.childCount; i++)
  908. {
  909. if (parent.GetChild(i) == tr)
  910. {
  911. // Subtract one to account for template child.
  912. selectedIndex = i - 1;
  913. break;
  914. }
  915. }
  916. if (selectedIndex < 0)
  917. return;
  918. value = selectedIndex;
  919. Hide();
  920. }
  921. }
  922. }