PopupAttribute.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. using UnityEngine;
  2. #if UNITY_EDITOR
  3. using UnityEditor;
  4. using System;
  5. #endif
  6. public class PopupAttribute : PropertyAttribute
  7. {
  8. public object[] list;
  9. public PopupAttribute (params object[] list)
  10. {
  11. this.list = list;
  12. }
  13. }
  14. #if UNITY_EDITOR
  15. [CustomPropertyDrawer(typeof(PopupAttribute))]
  16. public class PopupDrawer : PropertyDrawer
  17. {
  18. private Action<int> setValue;
  19. private Func<int, int> validateValue;
  20. private string[] _list = null;
  21. private string[] list
  22. {
  23. get
  24. {
  25. if (_list == null)
  26. {
  27. _list = new string[popupAttribute.list.Length];
  28. for (int i = 0; i < popupAttribute.list.Length; i++)
  29. {
  30. _list[i] = popupAttribute.list[i].ToString();
  31. }
  32. }
  33. return _list;
  34. }
  35. }
  36. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  37. {
  38. if (validateValue == null && setValue == null)
  39. SetUp(property);
  40. if (validateValue == null && setValue == null)
  41. {
  42. base.OnGUI(position, property, label);
  43. return;
  44. }
  45. int selectedIndex = 0;
  46. for (int i = 0; i < list.Length; i++)
  47. {
  48. selectedIndex = validateValue(i);
  49. if (selectedIndex != 0)
  50. break;
  51. }
  52. EditorGUI.BeginChangeCheck();
  53. selectedIndex = EditorGUI.Popup(position, label.text, selectedIndex, list);
  54. if (EditorGUI.EndChangeCheck())
  55. {
  56. setValue(selectedIndex);
  57. }
  58. }
  59. void SetUp(SerializedProperty property)
  60. {
  61. if (variableType == typeof(string))
  62. {
  63. validateValue = (index) =>
  64. {
  65. return property.stringValue == list[index] ? index : 0;
  66. };
  67. setValue = (index) =>
  68. {
  69. property.stringValue = list[index];
  70. };
  71. }
  72. else if (variableType == typeof(int))
  73. {
  74. validateValue = (index) =>
  75. {
  76. return property.intValue == Convert.ToInt32(list[index]) ? index : 0;
  77. };
  78. setValue = (index) =>
  79. {
  80. property.intValue = Convert.ToInt32(list[index]);
  81. };
  82. }
  83. else if (variableType == typeof(float))
  84. {
  85. validateValue = (index) =>
  86. {
  87. return property.floatValue == Convert.ToSingle(list[index]) ? index : 0;
  88. };
  89. setValue = (index) =>
  90. {
  91. property.floatValue = Convert.ToSingle(list[index]);
  92. };
  93. }
  94. }
  95. PopupAttribute popupAttribute
  96. {
  97. get { return (PopupAttribute)attribute; }
  98. }
  99. private Type variableType
  100. {
  101. get
  102. {
  103. return popupAttribute.list[0].GetType();
  104. }
  105. }
  106. }
  107. #endif