C# serializedObject变为空错误

C# serializedObject变为空错误,c#,unity3d,C#,Unity3d,在我的自定义编辑器中,我订阅了EditorApplication.update事件,以便在每个帧对我的对象进行一些填充: 使用UnityEngine; 使用UnityEditor; 使用制度; [CustomEditor(typeof(MyCustom))] [CaneditMultipleObject()] 公共类MyCustomEditor:Editor { private bool is_subcribed=假; void MyUpdate() { if(serializedObject=

在我的自定义编辑器中,我订阅了
EditorApplication.update
事件,以便在每个帧对我的对象进行一些填充:

使用UnityEngine;
使用UnityEditor;
使用制度;
[CustomEditor(typeof(MyCustom))]
[CaneditMultipleObject()]
公共类MyCustomEditor:Editor
{
private bool is_subcribed=假;
void MyUpdate()
{
if(serializedObject==null)
{
Log(“序列化对象为null”);
}
//我的代码
}
void OnEnable()
{
如果(!是_的子脚本)
{
EditorApplication.update+=MyUpdate;
is_subcribed=真;
}
}
}
它工作得很好,但是如果我转到父对象的预设(该没有此自定义编辑器),请选择其子对象自定义编辑器被选中时,已附加和自定义编辑器我退出预设模式就像
MyUpdate
函数继续调用自身和(因为那些子对象)未被选中,并且
serializibleObject
已不存在)将此疯狂抛入我的控制台:


我试图实现一些try/catch功能并取消订阅
EditorApplication.update
但我是C#新手,所以我失败了:(有人能帮我弹劾一下吗?

你没有删除侦听器。所以下次
EditorApplication.update
被称为你已经“销毁”了
MyUpdate
回调指向的编辑器实例将为
null

错误不会发生,因为
serializedObject
将是
null
,但回调项(您的
MyCustomEditor
实例) 在
EditorApplocation.update中
本身为
null


要删除回调,只需使用同一行,但使用
-=

注意:即使侦听器还不存在,也可以通过“save/”来删除它

// This is called when the object gains focus
private void OnEnable()
{
    // This makes sure the callback is added only once
    EditorApplication.update -= MyUpdate;
    EditorApplication.update += MyUpdate;
}

// This is called when the object loses focus or the Inspector is closed
private void OnDisable ()
{
    EditorApplication.update -= MyUpdate;
}

@derHugo的回答是正确的,但问题是在
MyUpdate
之后调用了
OnDisable
,因此我看到了一次错误消息。这并不重要,但我仍然建议尝试/捕获,以使控制台更清晰:

void OrbUpdate()
{
    try
    {
        MyCustom = (MyCustom)serializedObject.targetObject;
    }
    catch (Exception)
    {
        // Catching that bug :(
    }

}

private void OnDisable ()
{
    // And then unsubscribing
    EditorApplication.update -= MyUpdate;
}