這個是我自己的坑,自己挖的坑,然后自己跳了下去
首先上結論,以后別再犯同樣的錯誤:
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));

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/301370.html
標籤:其他
上一篇:飛機大戰C++
