- Home /
How do I make this switch destroy an object?
I'm trying to make a basic maze game, where going on a switch will 'open' a door, basically just destroying it using the OnTriggerEnter command. If the door has already been destroyed, nothing will happen, for which I just put in a Debug.Log line.
The main problem is "error CS0029: Cannot implicitly convert type `bool' to UnityEngine.GameObject'". I know there's probably a very simple solution here, but I just can't seem to get it right. Here's the code.
public class Switch : MonoBehaviour {
public GameObject door;
void OnTriggerEnter(Collider other) {
Debug.Log ("Door Open");
**if (door = true) {**
Destroy(door);
Debug.Log ("Door Open");
}
else{
Debug.Log("Already did that");
}
}
}
Problem line was bolded. Thanks ahead of time.
Answer by hoy_smallfry · Mar 08, 2013 at 12:47 AM
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!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to only delete one of two collided objects? 1 Answer
Help with destroying objects on collision 2 Answers
Why isn't OnTriggerEnter() called in the beginning of the game? 1 Answer