Unity 实现枚举多选

Unity 实现枚举多选

第一篇博客 2020.10.27

萌新工作了4个月,终于开始写第一篇技术文档。虽然是借鉴了别人的文档,但也加入了点自己的见解。对于我们这些新手,重要的是会用。轮子用的好,可以大量节省开发时间。

枚举多选

这个功能在实际开发中,其实很少用到。但大家在平常的使用中,其实经常遇到。摄像机Camera的Clear Flags 和Culling Mask属性都是典型的例子。它的作用在这里体现出来,当你的属性有很多值,并且这些值还可以多选时,使用枚举多选就非常方便了。

在这里插入图片描述
C#代码部分
在这里插入图片描述

第一部分
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum BookCount
{
One = 1,
Two = 2,
Three = 4,
Four = 8,
Five = 16,
Six = 32,
Seven = 64,
Eight = 128,
Nine = 256,
Ten = 512,
Eleven = 1024
}
public class EnumTenToTwo : MonoBehaviour
{

[EnumFlags]
public BookCount bookCount;
public static EnumTenToTwo instance;
void Awake()
{
    instance = this;
}
// Start is called before the first frame update
void Start()
{
    SwitchState(bookCount);
}

// Update is called once per frame
void Update()
{

}
public void Number()
{
}
private void SwitchState(BookCount type)
{
    if ((BookCount.One & type) == BookCount.One)     //&判断type是否存在one这个枚举,与one做判断,
    {

        Debug.Log("我进入One环节");
    }
    if ((BookCount.Two & type) == BookCount.Two)
    {

        Debug.Log("我进入Two环节");
    }
    if ((BookCount.Three & type) == BookCount.Three)
    {

        Debug.Log("我进入There环节");
    }
    if ((BookCount.Four & type) == BookCount.Four)
    {

        Debug.Log("我进入Four环节");
    }

    if ((BookCount.Five & type) == BookCount.Five)
    {

        Debug.Log("我进入Five环节");
    }

    if ((BookCount.Six & type) == BookCount.Six)
    {

        Debug.Log("我进入Six环节");
    }

    if ((BookCount.Seven & type) == BookCount.Seven)
    {

        Debug.Log("我进入Seven环节");
    }

    if ((BookCount.Eight & type) == BookCount.Eight)
    {

        Debug.Log("我进入Eight环节");
    }

    if ((BookCount.Nine & type) == BookCount.Nine)
    {

        Debug.Log("我进入Nine环节");
    }

    if ((BookCount.Ten & type) == BookCount.Ten)
    {

        Debug.Log("我进入Ten环节");
    }
     if ((BookCount.Eleven & type) == BookCount.Eleven)
    {

        Debug.Log("我进入Eleven环节");
    }
}

}

第二部分
using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(EnumFlags))]
public class EnumFlagsAttributeDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
property.intValue = EditorGUI.MaskField(position, label, property.intValue
, property.enumNames);

    //Debug.Log("图层的值:" + property.intValue);
}

}
第三部分

using UnityEngine;

public class EnumFlags : PropertyAttribute
{

}

把EnumTenToTwo 挂载游戏物体上,点选枚举,运行看效果。
在这里插入图片描述
在这里插入图片描述
隔了几天才发现一个很重要的问题,UnityEditor(编辑器扩展是无法参加打包的)。也就是说,我上面引用了UnityEditor的EnumFlagsAttributeDrawer类打包会报错。你需要重新建一个名叫Editor的文件夹,然后把EnumFlagsAttributeDrawer丢进去,再打包,你就会发现打包成功!完美解决~

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值