1
\$\begingroup\$

I was reading that Unity does not store GameObjects being null literally, but instead overloads the == operator.

For this reason the null coalescence operators ?? ??= don't work on GameObjects or Components

But if GameObjects and Components are never set to the literal value null, and instead == is overloaded, is it unsafe to do a null check if(component != null) as if(component)? The latter option compiles and seems to work fine, but I don't understand why if it's not ever the value 0, and if this will actually cause problems down the line

\$\endgroup\$
1
  • 1
    \$\begingroup\$ If you're trying to skip the overloaded comparison operator, (and you're sure you're not dealing with an object that might have been Destroy()ed or filled-in by an editor placeholder) you can also use System.Object.ReferenceEquals(myComponent, null) \$\endgroup\$
    – DMGregory
    Commented Jul 27, 2020 at 13:06

1 Answer 1

2
\$\begingroup\$

Yes, because GameObject inherits Object that implements a conversion to bool, Object.bool, which is what gets evaluated when you write if (object).

The linked docs assert that the conversion behaves equally to operator!= which I assume in any sane world of boolean axioms behaves as !(operator==), meaning that the conversion behaves as operator==, not as System.Object.ReferenceEquals(gameObject, null).

\$\endgroup\$
1
  • \$\begingroup\$ Does this implicit conversion behave like the overridden == operator and report "false" for objects that have been Destroy()ed? Or does it behave like System.Object.ReferenceEquals(gameObject, null) and return false only for a "real" null? \$\endgroup\$
    – DMGregory
    Commented Jul 27, 2020 at 13:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .