Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity : this == null returns true. How can this happen? [duplicate]

I've been working on a project in unity and I'm trying to invoke a function with Invoke(string, float); though I get an error saying to check if my gameobject is null, so I tried doing

debug.log(gameObject == null); 

it returned with an error. I tried

debug.log(this == null);

result true?

Does anyone know how to fix this issue?

if(confetti != null)             
{                 
    confetti.Play();             
}             

if (this != null)             
{                 
    StartCoroutine("restart");             
}             
else 
    SceneManager.LoadScene("SampleScene");
like image 233
LucasA Avatar asked Aug 30 '25 16:08

LucasA


1 Answers

One unfortunate thing about Unity is that when you do == null on a Unity Object, you are not actually just checking for a null reference. For Unity Objects, == null will return true if the reference is null OR the object has been destroyed in the scene.

This is an important distinction because Unity Objects actually mostly live "in C++", and the objects you get in C# are mostly just wrappers.

See the accepted answer here

If you want to just check for a null reference and not if the Unity Object has been destroyed, do one of these:

  • Use is null / is not null syntax

  • Cast the Unity Object into a System.Object before doing == null check

  • Use object.ReferenceEquals(something, null)

  • Use a null coalescing operator

like image 65
Petrusion Avatar answered Sep 02 '25 10:09

Petrusion