3

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");
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
LucasA
  • 31
  • 1
  • 2

1 Answers1

7

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

Petrusion
  • 940
  • 4
  • 11