在我的自定义编辑器中,我订阅了EditorApplication.update
事件,以便对对象的每一帧进行一些处理:
using UnityEngine;
using UnityEditor;
using System;
[CustomEditor(typeof(MyCustom))]
[CanEditMultipleObjects()]
public class MyCustomEditor : Editor
{
private bool is_subcribed = false;
void MyUpdate()
{
if (serializedObject == null)
{
Debug.Log("serialized object is null");
}
// My code stuff
}
void OnEnable()
{
if(!is_subcribed)
{
EditorApplication.update += MyUpdate;
is_subcribed = true;
}
}
}
效果很好,但是如果我转到父对象的 Prefab (没有此CustomEditor),请选择其子对象),并且已附加此自定义编辑器,并且在选择它们时 ,我退出了预制模式似乎MyUpdate
函数会继续调用自身,并且(由于未选择那些子对象并且serializibleObject
已经消失),这种疯狂的行为进入了我的控制台:>
我曾尝试实现一些try / catch事情并取消订阅EditorApplication.update
,但是我是C#的新手,所以我失败了:(有人可以帮我实现吗?
答案 0 :(得分:1)
您不会删除侦听器。因此,下次调用EditorApplication.update
时,您已经“销毁了” MyUpdate
回调指向的编辑器实例,因此它将是null
。
不会发生错误,因为serializedObject
将是null
,但是是回调条目(您的MyCustomEditor
实例)
在EditorApplocation.update
中本身就是null
。
要删除回调,只需使用同一行,但改用-=
。
注意:始终“保存” /允许删除监听器,即使该监听器尚不存在。所以我会做
// 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;
}