- Home /
Why does if(component) work for null tests
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 litteral 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
Answer by Bunny83 · Jul 27, 2020 at 01:26 PM
Because when you check the documentation for the UnityEngine.Object base class you will find an implicit bool conversion operator. It's implemented like this. All operators are essentially static method which takes the corresponding operands as parameters. Type conversion operators are unary operators, so they only take a single operand.
An if statement expects a boolean value. Since the object you use in your if statement has an implicit conversion operator, the compiler will use it to convert the object into a bool value.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Why Sprite is null? 0 Answers
Making a bubble level (not a game but work tool) 1 Answer
An OS design issue: File types associated with their appropriate programs 1 Answer