我正在尝试开始使用 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
属性。 为什么会这样以及如何使其正常工作?
答案 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以来的第二种方式是引用对象,对其进行更改将更改所有引用该对象的其他对象。