DropDownControl.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using UnityEditor;
  3. using UnityEngine;
  4. namespace UnityTest
  5. {
  6. [Serializable]
  7. internal class DropDownControl<T>
  8. {
  9. private GUILayoutOption[] buttonLayoutOptions = new [] { GUILayout.ExpandWidth (true) };
  10. public Func<T, string> convertForButtonLabel = s => s.ToString ();
  11. public Func<T, string> convertForGUIContent = s => s.ToString ();
  12. public Func<T[], bool> ignoreConvertForGUIContent = t => t.Length <= 40;
  13. public Action<T> printContextMenu = null;
  14. public string tooltip = "";
  15. private object selectedValue;
  16. public void Draw (T selected, T[] options, Action<T> onValueSelected)
  17. {
  18. Draw (null,
  19. selected,
  20. options,
  21. onValueSelected);
  22. }
  23. public void Draw(string label, T selected, T[] options, Action<T> onValueSelected)
  24. {
  25. Draw (label, selected, ()=>options, onValueSelected);
  26. }
  27. public void Draw(string label, T selected, Func<T[]> loadOptions, Action<T> onValueSelected)
  28. {
  29. if (!string.IsNullOrEmpty (label))
  30. EditorGUILayout.BeginHorizontal ();
  31. var guiContent = new GUIContent (label);
  32. var labelSize = EditorStyles.label.CalcSize(guiContent);
  33. if (!string.IsNullOrEmpty(label))
  34. GUILayout.Label (label, EditorStyles.label, GUILayout.Width (labelSize.x));
  35. if (GUILayout.Button(new GUIContent(convertForButtonLabel(selected), tooltip),
  36. EditorStyles.popup, buttonLayoutOptions))
  37. {
  38. if (Event.current.button == 0)
  39. {
  40. PrintMenu(loadOptions());
  41. }
  42. else if (printContextMenu!=null && Event.current.button == 1)
  43. printContextMenu (selected);
  44. }
  45. if (selectedValue != null)
  46. {
  47. onValueSelected ((T) selectedValue);
  48. selectedValue = null;
  49. }
  50. if (!string.IsNullOrEmpty (label))
  51. EditorGUILayout.EndHorizontal ();
  52. }
  53. public void PrintMenu (T[] options)
  54. {
  55. var menu = new GenericMenu ();
  56. foreach (var s in options)
  57. {
  58. var localS = s;
  59. menu.AddItem(new GUIContent((ignoreConvertForGUIContent(options) ? localS.ToString() : convertForGUIContent(localS))),
  60. false,
  61. () => { selectedValue = localS;}
  62. );
  63. }
  64. menu.ShowAsContext ();
  65. }
  66. }
  67. }