这个是我自己的坑,自己挖的坑,然后自己跳了下去
首先上结论,以后别再犯同样的错误:
SerializedProperty.enumValueIndex得到的是当前枚举值在所有值中的排序索引,不是枚举值!!!是enumValueIndex,是Index!!!不是enumValue!
错误的写法:
public enum EventType
{
None = 0,
Test = 2,
Attack = 1,
Test3 = 3,
Damage = 4,
}
[System.Serializable]
public class ActionEvent
{
public EventType eventType;
public float atkValue;
public float damageValue;
}
public class Actor : MonoBehaviour
{
public ActionEvent actionEvent;
}
[CustomPropertyDrawer(typeof(ActionEvent), true)]
public class ActionEventDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
using (new EditorGUI.PropertyScope(position, label, property))
{
SerializedProperty eventType = property.FindPropertyRelative("eventType");
EditorGUI.PropertyField(position, eventType);
position.y += EditorGUIUtility.singleLineHeight;
//把enumValueIndex当成枚举值就是最大的错误
switch (eventType.enumValueIndex)
{
case (int)EventType.Attack:
EditorGUI.PropertyField(position, property.FindPropertyRelative("atkValue"));
break;
case (int)EventType.Damage:
EditorGUI.PropertyField(position, property.FindPropertyRelative("damageValue"));
break;
}
}
}
}
由于我的枚举被我从中间,删除了几个,导致枚举值不连续,因此最开始我使用Popup绘制时,一直以为是使用SerializedProperty.enumNames导致的问题,因为这个names是连续的数组,是对不上枚举值的,所以一直在这里改,一直没有注意到enumValueIndex的问题。
正确写法:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
[CustomPropertyDrawer(typeof(ActionEvent), true)]
public class ActionEventDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
using (new EditorGUI.PropertyScope(position, label, property))
{
SerializedProperty eventType = property.FindPropertyRelative("eventType");
EditorGUI.PropertyField(position, eventType);
position.y += EditorGUIUtility.singleLineHeight;
var eventTypeValue = Enum.GetValues(typeof(EventType)).GetValue(eventType.enumValueIndex);
switch (eventTypeValue)
{
case EventType.Attack:
EditorGUI.PropertyField(position, property.FindPropertyRelative("atkValue"));
break;
case EventType.Damage:
EditorGUI.PropertyField(position, property.FindPropertyRelative("damageValue"));
break;
}
}
}
}
我们在调试的窗口中可以看到枚举的值数组列:
var values = Enum.GetValues(typeof(FPSPlayerActionEventType));