BitMaskDrawer.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using UnityEngine;
  3. using UnityEditor;
  4. namespace HQFPSWeapons
  5. {
  6. [CustomPropertyDrawer(typeof(BitMask))]
  7. public class EnumBitMaskPropertyDrawer : PropertyDrawer
  8. {
  9. public override void OnGUI (Rect position, SerializedProperty prop, GUIContent label)
  10. {
  11. var attr = attribute as BitMask;
  12. prop.intValue = DrawBitMaskField(position, prop.intValue, attr.EnumType, label);
  13. }
  14. private int DrawBitMaskField(Rect position, int mask, Type type, GUIContent label)
  15. {
  16. var itemNames = Enum.GetNames(type);
  17. var itemValues = Enum.GetValues(type) as int[];
  18. int val = mask;
  19. int maskVal = 0;
  20. for(int i = 0; i < itemValues.Length; i++)
  21. {
  22. if (itemValues[i] != 0)
  23. {
  24. if ((val & itemValues[i]) == itemValues[i])
  25. maskVal |= 1 << i;
  26. }
  27. else if (val == 0)
  28. maskVal |= 1 << i;
  29. }
  30. int newMaskVal = EditorGUI.MaskField(position, label, maskVal, itemNames);
  31. int changes = maskVal ^ newMaskVal;
  32. for(int i = 0; i < itemValues.Length; i++)
  33. {
  34. if((changes & (1 << i)) != 0) // has this list item changed?
  35. {
  36. if((newMaskVal & (1 << i)) != 0) // has it been set?
  37. {
  38. if(itemValues[i] == 0) // special case: if "0" is set, just set the val to 0
  39. {
  40. val = 0;
  41. break;
  42. }
  43. else
  44. val |= itemValues[i];
  45. }
  46. else // it has been reset
  47. val &= ~itemValues[i];
  48. }
  49. }
  50. return val;
  51. }
  52. }
  53. }