Unity editor implements enumeration and multiple selection

Introduction:

In the editor, you can easily implement multiple selection of enumerations.

Customize enumeration properties in script

/// <summary>
/// 定义多选属性
/// </summary>
public class EnumMultiAttribute : PropertyAttribute { }

/// <summary>
/// 绘制多选属性
/// </summary>
[CustomPropertyDrawer(typeof(EnumMultiAttribute))]
public class EnumMultiAttributeDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        property.intValue = EditorGUI.MaskField(position, label, property.intValue
                                                , property.enumNames);
    }
}

At this time, you need to add attribute tags to the enumeration of multiple selections

/// <summary>
/// 测试枚举
/// </summary>
public enum EnumType
{
    One,
    Two,
    Three,
    Four
}


[Header("测试枚举")]
[EnumMultiAttribute]
public EnumType enumType;

A similar level of multi-selection effect can be achieved in the editor

If you need to determine whether a certain enumeration is selected, you need a shift operation

    //判断是否选择了该枚举值
    public bool IsSelectEnumType(EnumType type)
    {
        // 将枚举值转换为int 类型, 1 左移 
        int index = 1 << (int)type;
        // 获取所有选中的枚举值
        int eventTypeResult = (int)enumType;
        // 按位 与
        if ((eventTypeResult & index) == index)
        {
            return true;
        }
        return false;
    }

 

Guess you like

Origin blog.csdn.net/mango9126/article/details/102732813