|

Don’t compare floats or Vector3 variables directly

Since the float implementation in Unity is built for performance and not accuracy (which is why in the Editor you will often see weird values like 0.000000001 instead of 0), you should never compare float values with the equality operator such as:

if (floatVar == 0.5f) { ... }

…otherwise the result will most likely be false!

Solution: For float values, use the following:

Mathf.Approximately(val1, val2)

 

Related: For Vector3 use == instead of Equals() since a Vector3 is composed of three float values, the overloaded equality operator from Unity will perform approximation, whereas Equals() will compare exact values. That means you should compare this way (and not using .Equals()):

if (someVector == otherVector) { ... }

Similar Posts

Leave a Reply