Unity编辑器实现枚举多选

简介:

在编辑器中,可以很简单的实现枚举的多选。

在脚本中自定义枚举属性

/// <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);
    }
}

此时再需要多选的枚举上加上属性标签

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


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

编辑器中即可实现类似层级的多选效果

如果需要判断是否选中了某个枚举,需要位移操作

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

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值