从SerializedProperty中的类获取浮点数

时间:2019-04-07 10:05:31

标签: unity3d

我正在尝试开始使用 this talk 中所述的可加密对象。这是我的代码:

这是我的FloatVariable:

using UnityEngine;

[CreateAssetMenu]
public class FloatVariable : ScriptableObject
{
    public float value;
}

这是我的FloatReference:

using UnityEngine;
using System;

[Serializable]
public class FloatReference
{
    public bool use_constant = true;
    public float constant_value;
    public FloatVariable variable_value;

    public float v
    {
        get
        {
            return use_constant ? constant_value : variable_value.value;
        }
        set
        {
            if (use_constant) throw new Exception("Cannot assign constant_value");
            else variable_value.value = value;
        }
    }
}

这是我的GameplayManager,其中我有一个FloatReference值:

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
using System;


public class GameplayManager : MonoBehaviour
{
    public FloatReference pl_orb_mode;
}

这是我的GameplayManagerEditor,我在这里尝试从float类中获取FloatVariable

using UnityEngine;
using UnityEditor;
using System;

[CustomEditor(typeof(GameplayManager))]
public class GameplayManagerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        SerializedProperty pl_orb_mode = serializedObject.FindProperty("pl_orb_mode");
        SerializedProperty variable = pl_orb_mode.FindPropertyRelative("variable_value");
        SerializedProperty the_value = variable.FindPropertyRelative("value");

        float test = the_value.floatValue;
        Debug.Log(test);
    }

}

当我尝试获取float test = the_value.floatValue;时出现错误:

NullReferenceException: Object reference not set to an instance of an object
GameplayManagerEditor.OnInspectorGUI () (at Assets/Shared/Scripts/Editor/GameplayManagerEditor.cs:18)

所以我可以将FloatVariable variable类作为SerializedProperty来获取,但不能获取其value属性。 为什么会这样以及如何使其正常工作?

1 个答案:

答案 0 :(得分:1)

因为FloatVariable是从ScriptableObject继承的,所以variable_value成为引用而不是SerializedObject中的属性。

您有2个选择。

不要使用ScriptableObject:

[Serializable]
public class FloatVariable
{
    public float value;
}

或编辑参考对象:

var so = new SerializedObject(((GameplayManager)target).pl_orb_mode.variable_value);
var the_value = so.FindPropertyRelative("value");
...
so.ApplyModifiedProperties();

请注意,自FloatVariable以来的第二种方式是引用对象,对其进行更改将更改所有引用该对象的其他对象。