I'm having trouble with comparison of 2 float values in a C# script after having exhausted what I have seen as possible answers. Here is the code that assigns the value to the first float every FixedUpdate():
The other float is assigned a float value from another method. Its value never changes. I've tried the "==" comparison as well as Mathf.Approxmately(). I've also tried changing each of the hard-coded values from simple numbers (100) to decimals (100.0) and appending "f" to designate them as floats. I've tried many combinations of the above 3 in conjunction with the different comparison options but the comparison is NEVER evaluated as true.
You really shouldn't ever compare floats with ==, as soon as you do any maths with them they'll be different internally, even if they look similar
What you can do is make a simple function to check for equality within a tolerance, e.g.
function IsApproximately(a : float, b : float)
//lets you skip the tolerance to use a sane default value
{
return IsApproximately(a, b, 0.02);
}
function IsApproximately(a : float, b : float, tolerance : float)
{
return Mathf.Abs(a - b) < tolerance;
}
ALternatively, when you create your conditional statements, use the greater/less than operators, e.g:
if (myVal > -0.05 || myVal < 0.05) { /* do something */ }
The reason Mathf.Approximately isn't always too useful is that it's basically the function above, with Mathf.epsilon as the tolerance, which is the smallest possible float value, so it's not likely to be within it after a few sums