(统一)有没有办法在引用的对象实例获得deleted/missed时得到通知?

(Unity) Is there a way to get notified when referenced object instance gets deleted/missed?

假设我们有 MonoBehaviour class 和 Transform 属性:

public class Class : MonoBehaviour
{
    public Transform Target; //An object is already referenced here.
}

问题很简单:如果此对象被删除(外部),是否有办法获取事件或某种回调?

Unity 会将其显示为“缺失”:

因为它只是一个转换,你不能在这里真正使用 OnDestroy(),即使你可以,这也不是一个好的选择,因为有多少转换实例。

可序列化字段可以在运行时通过编辑器检查器更改,因此无法保证编译时。

按照建议,您可以这样做:

void OnValidate() {
    if (Target == null)
        throw new NullReferenceException();    
}

你也可以试试,启发于documentation例子(未调试):

using UnityEngine;
using System.Collections;
using UnityEditor;

// Creates a custom Label on the inspector for all the scripts named ScriptName
// Make sure you have a ScriptName script in your
// project, else this will not work.
[CustomEditor(typeof(Class))]
public class ClassEditor: Editor
{
    Class classInstance;
    protected void OnEnable() {
        classInstance = (Class)target;
    }
    public override void OnInspectorGUI()
    {
        //you can first try only uncommenting line below to check if this script is working
        //GUILayout.Label ("This is a Label in a Custom Editor");  
        
        if (classInstance.Target === null) {
            EditorUtility.DisplayDialog("Target transform missing");
        }
    }
}

不确定 Class 名称是否会产生冲突,如果是则更改 class 名称。也不确定组件在缺失时是否被评估为 null(null 和 missing 不一样),我认为代码明智是相同的并且两者都抛出 nullRef 异常,但你被告知控制台,如果它为空或丢失。
你可以试试看。希望它至少能给你带来帮助。最终问题留作作业:)