- Home /
Collision detection with switch/case
Hi, I'm trying to change a certain variable depending on what type of object my character is walking on. to do that I've used a collision function with switch/case. Problem is - when my character walks on a certain object, it get stuck on that case statement and the variable doesn't go back to its default value.
function OnCollisionEnter(collision : Collision) {
var obj=(collision.gameObject.name);
switch(obj){
case("EndingIndicator"):
Debug.Log("Ended");
break;
case("Bouncy_floor"):
isBounce=true;
break;
default:
isBounce=false;
break;
}
}
What am I doing wrong here? (I tried also naming the "default" object by name but that didn't work)...
Answer by Em3rgency · Jun 29, 2013 at 11:10 AM
You should read a but how a switch works... The default case activates only when none of the other cases are met. Meaning in your code, if there is a collision, but the object is none of the specified names, it defaults. What you want is for the value to go false when there no longer is a collision.
Use onCollisionExit() for that.
But it's still in collision when it's in default. This about it this way - It's a platform where the character is always walking across a certain object, and the default is the object that has no special characteristics. Plus as I said, I tried na$$anonymous$$g it specifically but that didn't work either.
Its supposed to be in collision when default. Your switch activates ONLY when there is a collision. As I said, you don't understand how the switch works.
Look, you need something like this...
Update()
{
if(colliding)
isBounce=true;
else
isBounce=false;
}
OnCollisionEnter()
{
colliding = true;
}
OnCollisionExit()
{
colliding = false;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613105125im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Syntax of switch + case insensitive? 2 Answers
Operator '==' cannot be used! 2 Answers
Saving drop down menu selection 1 Answer
Destroying Gate by hitting a switch 1 Answer
add case in swicth, from editor unity 0 Answers