EditorGUI.MaskField实现多选枚举
效果
枚举
public enum MyFontStyle { Bold, Italic, Outline, } public enum MyFontStyleMask { Bold = 1, Italic = 1 << 1, Outline = 1 << 2, }
标签类
using UnityEngine; public class MyEnumMaskAttribute : PropertyAttribute { }
Property Drawer
#if UNITY_EDITOR using System; using UnityEditor; using UnityEngine; [CustomPropertyDrawer(typeof(MyEnumMaskAttribute))] public class MyEnumMaskPropertyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty sp, GUIContent label) { var fieldType = fieldInfo.FieldType; if (!typeof(Enum).IsAssignableFrom(fieldType)) { position = EditorGUI.PrefixLabel(position, label); EditorGUI.LabelField(position, $"not Enum Type: {fieldType.Name}"); } else { string[] displayOpts = sp.enumNames; sp.intValue = EditorGUI.MaskField(position, label, sp.intValue, displayOpts); } } } #endif
测试代码
public class MyEnumMaskTest : MonoBehaviour { [MyEnumMask] public int m_Value; [MyEnumMask] public MyFontStyle m_FontStyleFlags; [MyEnumMask] public MyFontStyleMask m_FontStyleFlags2; void Start() { Debug.Log($"{(int)m_FontStyleFlags}, {Convert.ToString((int)m_FontStyleFlags, 2).PadLeft(32, '0')}"); Debug.Log($"Bold: {IsBitChecked(MyFontStyle.Bold)}"); Debug.Log($"Italic: {IsBitChecked(MyFontStyle.Italic)}"); Debug.Log($"Outline: {IsBitChecked(MyFontStyle.Outline)}"); Debug.Log($"=========="); Debug.Log($"{(int)m_FontStyleFlags2}, {Convert.ToString((int)m_FontStyleFlags2, 2).PadLeft(32, '0')}"); Debug.Log($"Bold: {0 != (m_FontStyleFlags2 & MyFontStyleMask.Bold)}"); Debug.Log($"Italic: {0 != (m_FontStyleFlags2 & MyFontStyleMask.Italic)}"); Debug.Log($"Outline: {0 != (m_FontStyleFlags2 & MyFontStyleMask.Outline)}"); } private bool IsBitChecked(MyFontStyle bit) { int mask = 1 << (int)bit; return 0 != ((int)m_FontStyleFlags & mask); } }
参考
Unity 编辑器扩展十 多选枚举 - 简书 (jianshu.com)