Unity Vector Comparison Rant
I recently ran into an interesting Unity feature that I didn’t know about previously. I kept having an agent get stuck in the same place for no apparent reason. I’ve spent two days trying to track down the problem and finally ran across this in the least expected place – a function written almost on day 1 of this project, over a year and a half ago.
I’m trying to set my x position to 32. Since I’m generating an event when the position changes I only want to change it if the value being passed is actually different. Looking at the various values in the debugger the position is indeed different. Comparing the previous and new x values directly indeed shows that they are not equal, but when comparing the vectors themselves they come out as equal!
I went to answers.unity3d.com to ask a question about it, but did due diligence first and searched for a similar problem and found a reference to vector equality operator documentation. The key verbiage is:
This will also return true for vectors that are really close to being equal.
All I can say is wtf?
Now, I understand why they did this – floating point rounding and precision and all that. But to put that functionality in an actual equality operator, which is supposed to be testing for equality, is not the proper way to handle that. It is surprising and unexpected behavior. Adding an Approximately method would have been a much better choice, like they did for floats in Mathf.Approximately.
I need my vector value to change to the integer values. I expect the equality operator to actually check for equality. The fact that it does not cost me two days trying to find a bug that should not have existed.
End of rant. On the plus side, I now have a nice and robust code tracing system for more easily tracking down this sort of thing in the future. Silver linings and all that.
One thought on “Unity Vector Comparison Rant”
Comments are closed.