- Home /
How to check if something is null?
Hey guys I have a script that creates joysticks, the problem is that when I load anoter level, this error appears:
MissingReferenceException: The object of type 'GUITexture' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
How can I make sure to make it null?
Answer by yoyo · Mar 09, 2011 at 06:20 PM
In C# you need to compare to null ...
if (myTexture != null)
GUI.DrawTexture(Rect(0,0,500,500),myTexture);
You don't need to do that nether in c# nor Java . "if (myTexture)" is equal to "if (myTexture != null)" in both languages .
I didn't believe you so I went and tried for myself -- you're right, thanks Ali! Turns out UnityEngine.Object has an implicit operator for conversion to boolean, which makes this work. Normally in C# you have to explicitly compare with null -- for example you can't say "if (myString)" (assu$$anonymous$$g myString is a string), you need to be explicit and say "if (myString == null)". I'd suggest using comparison with null even though its not necessary, otherwise you will be confused when it doesn't work for a non-Unity object.
Answer by AliAzin · Mar 09, 2011 at 06:10 PM
you can simply check it like this:
if (myTexture)
GUI.DrawTexture(Rect(0,0,500,500),myTexture);
Where could i read about this case of if statement: if (myTexture)
I want to be shure, that it is equivalent of if (myTexture != null)
Thank you!
This is the same, indeed. Here is the code of the UnityEngine.Object
class every objects derive from :
// Does the object exist?
// Called when checking `if (myTexture)`
public static implicit operator bool(Object exists)
{
return !CompareBaseObjects(exists, null);
}
// Called when checking if( myTexture != null )
public static bool operator!=(Object x, Object y) { return !CompareBaseObjects(x, y); }
Answer by Matheuz · Apr 07, 2020 at 07:30 PM
If you want to check if the underlying object has been destroyed:
if (_yourTexture != null)
If you want to check for actual null reference:
Object.ReferenceEquals (_myTexture, null)
Keep in mind that your example threw a MissingReferenceException and not a NullPointerException. These might look like the same, but they mean different things. On NullPointerExceptions, the variable actually points to null. On MissingReferenceException, the underlying object might have been destroyed, but the script might still leave. This article explains the difference between them.