首先是自定義
using UnityEngine; using System.Collections; using UnityEditor; public class EnumFlagsAttribute : PropertyAttribute {} [CustomPropertyDrawer(typeof(EnumFlagsAttribute))] public class EnumFlagsAttributeDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { /* * 繪制多值枚舉選擇框,0 全部不選, -1 全部選中, 其他是枚舉之和 * 枚舉值 = 當前下標值 ^ 2 * 默認[0^2 = 1 , 1 ^2 = 2, 4, 16 , .....] */ property.intValue = EditorGUI.MaskField(position, label, property.intValue , property.enumNames); } }
然后是腳本
using UnityEngine; using System.Collections; public enum LayerMaskEnum { Layer1, Layer2, Layer3, Layer4, Layer5, Layer6, Layer7, Layer8, Layer9, Layer10 } public class MyWdsCompoment : MonoBehaviour { [EnumFlagsAttribute] public LayerMaskEnum layer; [ContextMenu("輸出Layer值")] public void DebugPrint() { Debug.Log("layer="+(int)layer); Debug.Log(IsSelectEventType(LayerMaskEnum.Layer10)); } //判斷是否選擇了該枚舉值 public bool IsSelectEventType(LayerMaskEnum _eventType) { // 將枚舉值轉換為int 類型, 1 左移 int index = 1 << (int)_eventType; // 獲取所有選中的枚舉值 int eventTypeResult = (int)layer; // 按位 與 if ((eventTypeResult & index) == index) { return true; } return false; } }