DrawBitMaskField.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #if UNITY_EDITOR
  2. using UnityEngine;
  3. using UnityEditor;
  4. namespace FirstGearGames.Utilities.Editors
  5. {
  6. /// <summary>
  7. /// SOURCE: https://answers.unity.com/questions/1477896/assign-enum-value-from-editorguienumflagsfield.html
  8. /// </summary>
  9. public static class EditorExtension
  10. {
  11. public static int DrawBitMaskField(Rect aPosition, int aMask, System.Type aType, GUIContent aLabel)
  12. {
  13. var itemNames = System.Enum.GetNames(aType);
  14. var itemValues = System.Enum.GetValues(aType) as int[];
  15. int val = aMask;
  16. int maskVal = 0;
  17. for (int i = 0; i < itemValues.Length; i++)
  18. {
  19. if (itemValues[i] != 0)
  20. {
  21. if ((val & itemValues[i]) == itemValues[i])
  22. maskVal |= 1 << i;
  23. }
  24. else if (val == 0)
  25. maskVal |= 1 << i;
  26. }
  27. int newMaskVal = EditorGUI.MaskField(aPosition, aLabel, maskVal, itemNames);
  28. int changes = maskVal ^ newMaskVal;
  29. for (int i = 0; i < itemValues.Length; i++)
  30. {
  31. if ((changes & (1 << i)) != 0)
  32. {
  33. if ((newMaskVal & (1 << i)) != 0)
  34. {
  35. if (itemValues[i] == 0)
  36. {
  37. val = 0;
  38. break;
  39. }
  40. else
  41. val |= itemValues[i];
  42. }
  43. else
  44. {
  45. val &= ~itemValues[i];
  46. }
  47. }
  48. }
  49. return val;
  50. }
  51. }
  52. [CustomPropertyDrawer(typeof(BitMaskAttribute))]
  53. public class EnumBitMaskPropertyDrawer : PropertyDrawer
  54. {
  55. public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
  56. {
  57. var typeAttr = attribute as BitMaskAttribute;
  58. // Add the actual int value behind the field name
  59. label.text = label.text + " (" + prop.intValue + ")";
  60. prop.intValue = EditorExtension.DrawBitMaskField(position, prop.intValue, typeAttr.propType, label);
  61. }
  62. }
  63. }
  64. #endif