It’s easy to make dumb mistakes when you’re coding. Like here’s one I always make.
Say I have a slider for the interface with a knob in the middle you can slide back and forth. I need to check the position of the knob to see if it has moved left or right.
So I’m always tempted to do:
void CheckSliderPos() {
if (myKnob.transform.localposition.x > 5f) {
// do some stuff cuz the knob x pos is greater than 5 now
} else if (myKnob.transform.localposition.x < 3f) {
// do some stuff cuz the knob x pos is less than 3 now
}
}
So what's wrong with this? Usually, NOTHING! And that's the problem. Usually this sort of check is just fine. But what if there are more things to check? What if there is a whole list of if thens. And then what if the user slides the knob REALLY FAST?
Well, in this case there is the rare possibility that the user SLIDES THE SLIDER faster than the machine can compute the code. And this leads to ugly bugs.
So imagine this:
void CheckSliderPos() {
// THE FIRST CHECK OF THE SLIDER
if (myKnob.transform.localposition.x > 5f) {
// do some stuff cuz the knob x pos is greater than 5 now
// AND NOW PRETEND THERE A BUNCH OF OTHER LOGIC CHECKS...
// } else if { (etc)
// } else if { (etc)
// } else if { (etc)
// AND PRETEND THE USER SLID THE KNOB REALLY FAST...
// Do you see the problem?
// PROBLEM!!!!
// BY THIS POINT, the knob position may very likely have changed significantly from
// where it was when we checked at the top.
} else if (myKnob.transform.localposition.x < 3f) {
// do some stuff cuz the knob x pos is less than 3 now
}
}
This can quickly lead to whacky results.
The proper way to do it, of course, is to STORE the knob position immediately as a constant... and use the same constant to check against all the logic.
Like so:
void CheckSliderPos() {
// STORE THE POSITION so we can compare against a CONSTANT position
float knobXPos = myKnob.transform.localposition.x;
// THEN check your logic and you'll be fine.
if (knobXPos > 5f) {
// etc
} else if (knobXPos < 3f) {
// etc
}
}
This is such an easy and basic mistake, but I find myself making it all the time. A great example, I think, of how there are little tricky pitfalls in coding that can surprise you if you're not carefully thinking everything through.
Comments (0)