- Home /
Bool statement returns true, while conditions is false in IF statement
I'm bit puzzled. I got a script segment that rotates transform until it reaches certain angle. And it goes like this:
void Update(){
if (transform.localEulerAngles.y!=( transferingAngle))
{
angleTransfer(transferingAngle);
Debug.LogError("transform.localEulerAngles.y=" + ugo.coloredText("" + transform.localEulerAngles.y.ToString(), "0020d0") +
", transferingAngle=" + ugo.coloredText("" + transferingAngle.ToString(), "0020d0") +
", transform.localEulerAngles.y != transferingAngle is: " +
ugo.coloredText("" + (transform.localEulerAngles.y != transferingAngle), "0020d0"));
}
else
{
}
}
So every frame this fragment updates and checks if transform.localEulerAngles.y equals transferingAngle value. If so, else executes. This piece of code worked perfectly until that day.
I've set transferingAngle=50, and bool statement starts to gone wild. It says that values are unequal even if they are: Alas, the other values worked fine, like 310:
I "kinda" solved this problem when I set value to 51, but it doesn't solve it in general. I guess the trouble somewhere in numbers, but I don't know where exactly.
Comparing floats is not advised this way. Ins$$anonymous$$d you should check whether the absolute value of the difference is lower than a threshold. Fortunately for you, Unity already provides this function for you:
if ( !$$anonymous$$athf.Approximately( transform.localEulerAngles.y, transferingAngle ) )
If the threshold used by Unity is too small:
if ( $$anonymous$$athf.Abs( transform.localEulerAngles.y - transferingAngle ) < threshold ) // 0.001 for instance
If you are going to use the second approach a lot (it's a good approach so that will probably happen) then I recommend creating an extension method for it. It will spare you a lot of headaches, trust me.
Answer by Taylor-Libonati · Mar 07, 2019 at 11:07 PM
As people mentioned in comments. Comparing two floats is unreliable because they could be fractions of a number different. Instead you should do something like this
if ( Mathf.Abs( transform.localEulerAngles.y - transferingAngle ) < threshold )
The reason your logs are confusing is because you are not printing out the decimal places. so one angle could be 50.00000001 and the other is 50. And just so you know, when you log a float in unity by default it won't show every decimal place.