Unity 编辑器枚举值的获取和设置

665 阅读1分钟

原因

在 Unity 中为脚本的枚举变量做编辑器时,如果枚举定义不是按顺序的,那么就不方便设置值。Editor下的SerializedProperty字段,其enumValueIndex值是按enumNames的顺序,所以需要进行转换。

解决

封装接口来进行转换:

    public static T PropertyGetEnum<T>(SerializedProperty property)
    {
        return (T)Enum.Parse(typeof(T), property.enumNames[property.enumValueIndex]);
    }

    public static void PropertySetEnum(SerializedProperty property, Enum enumValue)
    {
        for (int i = 0; i < property.enumNames.Length; i++)
        {
            if (property.enumNames[i] == enumValue.ToString())
            {
                property.enumValueIndex = i;
                break;
            }
        }
    }