1) You’re trying to assign the boolean value true
to door instead of checking if they are the same. There’s a distinct difference between =
and ==
.
The =
operator assigns a value, like so:
int i = 1;
The ==
operator compares if two values of the same type are equal, and returns a bool
, like so:
bool b = 1 == 3;
if(b)
{
Debug.Log("they are equal!");
}
else
{
Debug.Log("they aren't equal!");
}
The !=
operator, on the other hand, does the exact opposite - compares if two values of the same type are not equal:
bool b = 1 != 3;
if(b)
{
Debug.Log("they aren't equal!");
}
2) C# is a strong-typed language, which means two unrelated types can’t become other types like they do in Javascript or Lua, at least not without some coercion. If you are declaring a value as a GameObject
, such as door
, it will be a GameObject
for the entirety of its existence.
That said, you are trying to assign door
(a GameObject
type) the value true
(which is for bool
types). This is like shoving a banana into a keyhole and expecting it to fit, let alone work.
The only time you can make the value of one type into the value of another is if you cast from one to the other, implicitly or explicitly. This works only if the types are allowed to, which explains the error you are getting; bool
and GameObject
can’t.
3) GameObject
and all other C# classes are reference types, which means the variable is currently referring to something in memory, or its not. If it is not referring to something that exists, then it’s value is null
.
All that said, your problem line should most probably be replaced with this:
// if the door exists
if(door != null)
This is the C# way of checking if the object has been initialized.
Hope that helps!