问题描述
我在 Unity 2020.2.1f1 中设置了一个非常简单的编辑器脚本,按下检查器按钮后,它应该将指定参数的值更改为代码中设置的值。
public override void OnInspectorGUI()
{
DrawDefaultInspector();
StateObject s = (StateObject)target;
if (s.objID == 0)
{
if (GUILayout.Button("Generate Object ID"))
{
GenerateID(s);
}
}
}
public void GenerateID(StateObject s)
{
s.objID = DateTimeOffset.Now.ToUnixTimeSeconds();
}
这一切都像它应该的那样工作。我按下按钮,正确的数字出现在字段中,我很高兴。但是,一旦我切换到播放模式,该值将重置为预制默认值,即使我关闭播放模式也保持这种状态。
我是不是遗漏了某些 ApplyChange 函数之类的东西?
解决方法
在我看来,比从编辑器脚本中混合直接访问要好,然后手动将事情标记为脏而不是通过 SerializedProperty
并让检查员处理这一切(还有标记为脏和保存更改,处理撤消/重做等)
SerializedProperty id;
private void OnEnable()
{
id = serializedObject.FindProperty("objID");
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
// Loads the actual values into the serialized properties
// See https://docs.unity3d.com/ScriptReference/SerializedObject.Update.html
serializedObject.Update();
if (id.intValue == 0)
{
if (GUILayout.Button("Generate Object ID"))
{
id.intValue = DateTimeOffset.Now.ToUnixTimeSeconds();
}
}
// Writes back modified properties into the actual class
// Handles all marking dirty,undo/redo,etc
// See https://docs.unity3d.com/ScriptReference/SerializedObject.ApplyModifiedProperties.html
serializedObject.ApplyModifiedProperties();
}
,
(编辑:这有效,但不如接受的答案。)
嗯,是的,我实际上缺少某种 ApplyChange 函数。
我不知道我是怎么错过的,但我一直在寻找这个:
EditorUtility.SetDirty(target);
所以,在我的脚本中,我只需要编辑 GenerateID 函数:
public void GenerateID(StateObject s)
{
s.objID = DateTimeOffset.Now.ToUnixTimeSeconds();
EditorUtility.SetDirty(s);
}
我将其发布在这里以防万一有人遇到同样的问题,这样他们希望在被提醒 SetDirty 是一个问题之前不必花费太多时间寻找解决方案。