VFXEnumField.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System;
  4. using UnityEngine;
  5. using UnityEngine.UIElements;
  6. using UnityEditor.VFX.UI;
  7. namespace UnityEditor.VFX.UIElements
  8. {
  9. class VFXEnumField : ValueControl<int>
  10. {
  11. Label m_DropDownButton;
  12. TextElement m_ValueText;
  13. System.Type m_EnumType;
  14. public IEnumerable<int> filteredOutValues { get; set; }
  15. public Action<VFXEnumField> OnDisplayMenu;
  16. void CreateHierarchy()
  17. {
  18. AddToClassList("unity-enum-field");
  19. m_DropDownButton = new Label();
  20. m_DropDownButton.AddToClassList("unity-enum-field__input");
  21. m_DropDownButton.AddManipulator(new DownClickable(OnClick));
  22. m_ValueText = new TextElement();
  23. m_ValueText.AddToClassList("unity-enum-field__text");
  24. var icon = new VisualElement() { name = "icon" };
  25. icon.AddToClassList("unity-enum-field__arrow");
  26. m_DropDownButton.Add(m_ValueText);
  27. m_DropDownButton.Add(icon);
  28. }
  29. void OnClick()
  30. {
  31. if (OnDisplayMenu != null)
  32. OnDisplayMenu(this);
  33. GenericMenu menu = new GenericMenu();
  34. foreach (string val in System.Enum.GetNames(m_EnumType))
  35. {
  36. int valueInt = (int)System.Enum.Parse(m_EnumType, val);
  37. if (filteredOutValues == null || !filteredOutValues.Any(t => t == valueInt))
  38. menu.AddItem(new GUIContent(ObjectNames.NicifyVariableName(val)), valueInt == m_Value, ChangeValue, valueInt);
  39. }
  40. menu.DropDown(m_DropDownButton.worldBound);
  41. }
  42. void ChangeValue(object val)
  43. {
  44. SetValue((int)val);
  45. if (OnValueChanged != null)
  46. {
  47. OnValueChanged();
  48. }
  49. }
  50. public VFXEnumField(string label, System.Type enumType) : base(label)
  51. {
  52. CreateHierarchy();
  53. if (!enumType.IsEnum)
  54. {
  55. Debug.LogError("The type passed To enumfield must be an enumType");
  56. }
  57. m_EnumType = enumType;
  58. style.flexDirection = FlexDirection.Row;
  59. Add(m_DropDownButton);
  60. var icon = new VisualElement() { name = "icon" };
  61. icon.AddToClassList("unity-enum-field__arrow");
  62. m_DropDownButton.Add(icon);
  63. }
  64. public VFXEnumField(Label existingLabel, System.Type enumType) : base(existingLabel)
  65. {
  66. CreateHierarchy();
  67. if (!enumType.IsEnum)
  68. {
  69. Debug.LogError("The type passed To enum field must be an enumType");
  70. }
  71. m_EnumType = enumType;
  72. Add(m_DropDownButton);
  73. }
  74. protected override void ValueToGUI(bool force)
  75. {
  76. m_ValueText.text = ObjectNames.NicifyVariableName(System.Enum.GetName(m_EnumType, m_Value));
  77. }
  78. }
  79. }