Null reference exception, but the object is not really null...

I’m having a strange issue with null references, maybe someone can help clear this up.

I’m expecting my reference to the object to become null at some point, however I need to do a check on the same object in a different class in order to make sure it’s not used. For some reason the regular “== null” check doesn’t work. However a string check does work.

If I access the object in any way, I get a NullReferenceException.

The following are three different checks I tried (the middle one really a guess). The last one (the string check) is the only one actually working. This is obviously not an efficient way to do this check, so I want to understand what’s really going on in order to fix this.

// My object is held in a standard object type as a member of the class
object myObject

...

// DOESN'T WORK
if(myObject == null)
	return true;
	
// DOESN'T WORK
if(UnityEngine.Object.ReferenceEquals(myObject, null))
	return true;
		
// WORKS!
if(myObject.ToString().Equals("null"))
	return true;

Here is more information from the debugger… looks null :confused:

Please help :frowning:

You have not provided enough code for anyone to determine why this is happening.

I can’t post the entire project or the entire class (also it’s counter productive).

myObject can be any kind of unity object (in this case it’s a RigidBody). It’s being destroyed in a different piece of code along with its GameObject.
This second class is using the same object for some generic manipulations (that’s why I use an “object” type). I can’t use a specific type here.

Basically I don’t understand how a toString() call would return a “null” string, but a “== null” comparison wouldn’t return a TRUE statement… There’s nothing else special going on here other than using a generic “object” type and that the holder GameObject is being destroyed in a different class.

Could it be the usage of “object” type? I’m really unsure how Unity implements the automatic nulling of objects. Is there a different way to compare for null?

Problem solved.

Replaced C# object with Unity’s UnityEngine.Object . Works perfectly now.

I was just testing it and was able to replicate the problem you had. Glad to see you found a solution.

The error message itself gives you a hint as well. The object itself isn’t null… but it has been destroyed and will be removed first chance it gets. A good example of this are things in C# that use IDisposable. If you have a class called MyClass that implements IDisposable, you could do this:

var mc = new MyClass();
mc.Dispose();

if(mc == null)
return true;

Unless the GC ran immediately, mc would not be null, but you couldn’t use it either because it’s been Disposed and marked for Finalization by the Garbage Collector.

I just use if(myObject != null)

Guys thanks for the help but the issue was solves. Please look a few posts up.