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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM