Search code examples
c#unity-game-engineunity-editor

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


So let's say we have MonoBehaviour class with a Transform property:

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

Question is simple: is there a way to get an event or some sort of callback in case this object gets deleted (externally)?

Unity will show this as "Missing":

1

Since it is just a transform, you cannot really use OnDestroy() here, and even if you could this is not a good option because of how many transform instances there are.


Solution

  • Serializable fields can be changed at runtime via editor inspectors, so compile time guarantees are not possible.

    As adviced, you can do:

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

    You can also try, inspired in the documentation example (not debugged):

    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");
            }
        }
    }
    

    Not sure if the Class name can give a conflict, change the class name if so. Also not sure if the component is evaluated to null when its missing (null and missing are not the same), I think that code wise is the same and that the nullRef exception is thrown for both, but you are told in the console if its null or missing.
    You can try that out. Hope it may at least gide you. Eventual problems are left as homework :)