Two Vector3 comparations doesnt work.
Hi guys,
this must be a really stupid problem. When I print Vector3 values as bellow, console says it is (0.0, 0.0, 0.0):
print (transform.position - player.transform.position - cameraPosition);
when I try to compare two Vectors according to this link this code doesnt work:
if(transform.position - player.transform.position - cameraPosition == Vector3.zero)
print("yes");
Anybody knows why?
There are two things going on here. Look up how debug displays Vector3 (try "unity debug Vector3") and also look up comparing floats.
Answer by DiegoSLTS · Oct 10, 2015 at 03:45 PM
When you print a Vector3, the numbers shown are formated to display only 1 decimal point.
Each component is close to zero, but not zero. Try printing each component like:
Vector3 aux = transform.position - player.transform.position - cameraPosition;
print(aux.x);
print(aux.y);
print(aux.z);
And you'll see it.
Anyway, comparing floats for equality is a known problem, you should never do that. Instead, check if the 2 values are close enough or, in other words, if the distance between 2 floats is close enough to zero.
There are multiple approachs for this, in your case I'd do:
Vector3 aux = transform.position - player.transform.position - cameraPosition;
if( aux.sqrMagnitude < 0.01f) //set a proper value, 0.01f is just an example
print("yes");
Your answer
![](https://koobas.hobune.stream/wayback/20220612040801im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to compare limits for creating new objects in world space? 0 Answers
Unity Hanging when Changing a Vector3.x 2 Answers
How to make object land on certain point?,How to make object land on certain point?? 0 Answers
instantiate keeps repeating itself 0 Answers
How to Stack, Shuffle and deal cards 0 Answers