【问题标题】:Get and Set System.Object value using Unity SerializedProperties使用 Unity SerializedProperties 获取和设置 System.Object 值
【发布时间】: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


【解决方案1】:

恐怕,截至 Unity 2019.2 和撰写此答案时,这是不可能直接使用未注册为 serialisedProperties 的对象或其他类型的,但是仍然可以通过变通方法来完成。

上述解决方法包括(ab)使用ISerializationCallbackReceiver 接口and thus circumvent this issue,通过为编辑器使用可延展的中间表示。这确实有效!

关于部分切线:如果使用序列化属性的东西,您可以通过使用反射来use hacks to access the value directly。例如,如果您希望在编辑器中手动调用自定义类的 OnBeforeSerialize 方法,这对我们的例子很有帮助。

【讨论】:

    猜你喜欢
    • 2021-04-18
    • 2023-03-08
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2021-01-31
    相关资源
    最近更新 更多