- Home /
If statement not working inside switch statement
Here is the code I'm using
private void OnTriggerEnter(Collider other) // Player interacts with objects when he enters colliders
{
switch (other.gameObject.tag)
{
case "Green":
print("Green Crystal!");
if (Input.GetKey(KeyCode.Space)) // The If statement is not working for some reason
{
Destroy(green);
}
break;
case "Blue":
print("Blue Crystal!");
if (Input.GetKey(KeyCode.Space))
{
Destroy(blue);
}
break;
For your information, the print function works yet when it comes to the if statement, nothing happens.
Answer by Bunny83 · Dec 03, 2019 at 12:41 AM
How do you come to the conclusion that the if statement doesn't work? Just because you don't get your expected behaviour? Have you actually debugged that fact? So have you tried placing a print / Debug.Log statement inside the if body to see it you actually get there? We have no idea what green or blue represents.
Keep in mind that you have this code in OnTriggerEnter. So it will only be called once when you enter the trigger. That means you have to hold down the space key before you enter the trigger in order to get inside the if statement. If that's not the behaviour you want you probably use the wrong approach all together. You might wanted to use OnTriggerStay?
Thanks a lot, the problem indeed was in the OnTriggerEnter. Yes, it should be OnTriggerStay. Also, I tried holding space while entering the collider and the function I wanted worked properly. Thanks again.
Your answer
![](https://koobas.hobune.stream/wayback/20220612215618im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
I can't get 2DCollider to work. 1 Answer
Trouble with light switch 3 Answers
Destroy objects when key is pressed 1 Answer
OnTriggerEnter is not running! Need help with collision. 2 Answers
Destroyed prefab still moving 1 Answer