Unity C# 用枚举(enum)制作复选框

最近在项目中做测试脚本用到一些布尔值做方法的开关,突然想到可以制作一个复选框控制开关。

首先搜集网上的资料,基本大同小异,这里就不多做解释了,代码附上:

1 public class EnumFlagsAttribute : PropertyAttribute{}
 1 [CustomPropertyDrawer(typeof(EnumFlagsAttribute))]
 2 public class EnumFlagsDrawer:PropetyDrawer
 3 {
 4     public override void OnGUI(Rect position,SerializedProperty property,GUIContent label)
 5     {
 6         /*绘制枚举复选框 , 0-Nothing,-1-Everything,其他是枚举之和
 7         枚举值(2的x次幂):2的0次幂=1,2的1次幂=2,2的2次幂=4,8,16...
 8         */
 9         property.intValue = EditorGUI.MaskField(position,label,property.intValue,property.enumNames);
10     }
11 }

下面是应用:

 1 [System.Flags]
 2 public enum TestEnum
 3 {
 4     One=1,
 5     Two=2,
 6     Three=4,
 7     Four=8,
 8 }
 9 
10 public class testEnum
11 {
12     [EnumFlags]
13     public TestEnum _testEnum;
14     
15     if((int)(_testEnum&TestEnum.One)==1)
16         DoSomething1();
17     if((int)(_testEnum&TestEnum.Two)==2)
18         DoSomething2();
19     if((int)(_testEnum&TestEnum.Three)==4)
20         DoSomething3();
21     if((int)(_testEnum&TestEnum.Four)==8)
22         DoSomething4();
原文地址:https://www.cnblogs.com/AdvancePikachu/p/7729392.html