【发布时间】:2019-08-12 23:17:33
【问题描述】:
我希望能够使用枚举指定类型并将值分配给对象变量,但我不断收到“NullReferenceException ..”错误消息。
我有这个简单的课程:
[System.Serializable()]
public class ObjectValue
{
public enum ValueType { Null, Integar, Float, String, Boolean }
[SerializeField, HideInInspector] private ValueType type = ValueType.Null;
public object value = null;
}
借助属性抽屉脚本,我希望能够在 Inspector 上查看此类并根据所选类型编辑值:
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(ObjectValue))]
public class ObjectValue_Drawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return base.GetPropertyHeight(property, label) + 17;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
GUI.Box(position, GUIContent.none);
var typeEnum = property.FindPropertyRelative("type");
position.height = 17;
EditorGUI.PropertyField(position, typeEnum);
position.y += 17;
var value = property.FindPropertyRelative("value");
switch (typeEnum.enumValueIndex)
{
case (int)ObjectValue.ValueType.Null:
GUI.Label(position, "Null Value Type");
break;
case (int)ObjectValue.ValueType.Integar:
value.intValue = EditorGUI.IntField(position, "Value", value.intValue);
break;
case (int)ObjectValue.ValueType.Float:
value.floatValue = EditorGUI.FloatField(position, "Value", value.floatValue);
break;
case (int)ObjectValue.ValueType.String:
value.stringValue = EditorGUI.TextField(position, "Value", value.stringValue);
break;
case (int)ObjectValue.ValueType.Boolean:
value.boolValue = EditorGUI.Toggle(position, "Value", value.boolValue);
break;
}
}
}
【问题讨论】:
-
@BugFinder 这是不是关于空引用异常的一般问题的重复。在 Unity 检查器 UI 的上下文中,这是一个完全有效的问题,即使问题本身可以更好地阐明上下文。
标签: c# object unity3d types properties