unity 多選枚舉


 

首先是自定義

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

 


免責聲明!

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



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