I have a hypothesis for what might be causing this...
First, I need to explain something about
null in Unity: when an instance descended from
Destroy()ed, it does not actually become
(In C#, a variable will only hold a value of
null if it's uninitialized, or if it's been assigned
myVariable = null explicitly - nothing can delete the object out from under you as long as any active script holds a reference to it)
Destroy() takes effect at the end of the current frame's updates (before rendering), references to the instance will compare as equal to
null, because Unity overloads the
== operator for
UnityEngine.Object. But the reference is still non-null. Try this example:
var myObject = new GameObject();
Debug.Log("Is it null immediately?"
+ (myObject == null)); // false
yield return null; // Wait one frame for Destroy() to take effect
Debug.Log("NOW is it null? "
+ (myObject == null)); // true
Debug.Log("But is it *really* null? "
+ System.Object.ReferenceEquals(myObject, null)); // false
This "pseudo-null" stub is what lets Unity understand what you were trying to do and give you a tailored error message:
MissingReferenceException: The object of type 'InteractiveItem' has
been destroyed but you are still trying to access it.
null values look alike, so if it was a real
null Unity wouldn't be able to tell it came from a destroyed object.
Okay, so with that background, why is your code giving this confusing result?
Without seeing more of your code it's hard to say for sure, but I have a suspicion that you're implementing this interface on a
MonoBehaviour, and your
null check doesn't know it's working with a class descended from
UnityEngine.Object - all it knows is that it implements the
So this line:
return interacting != null;
is using the standard comparison, like
System.Object.ReferenceEquals(). That replies "Well, no, it's been
Destroy()ed, but it's not literally null" so
IsInteracting() returns true.
Then your code proceeds and tries to call
and Unity steps in to say "Why are you trying to access a member of a
MonoBehaviour?" and throws an error.
So, some possible fixes...
InteractiveItem descend from
MonoBehaviour if everything
implementing it is going to be a
MonoBehaviour anyway, so the
correct comparison is used automatically.
- Try casting
interacting to (something descended from...)
UnityEngine.Object before checking for
null to catch when it's
- Make your interactive objects aware that someone is trying to
interact with them, and use an
OnDestroy method to notify the
interactor when the interaction is no longer available.