Comparing two identical objects returns false in Unity 3D (C #)

I am writing a C # script in Unity 3D. I have two Vector3

that match. When I do this:

Debug.Log(vect1);
Debug.Log(vect2);

      

I am getting the same result (500.0, 150.0, 0.0)

. The problem is that when I do vect1.Equals(vect2)

, I become false! How is this possible?

PS I'm sure they both Vector3

, because when I do vect1.GetType()

and vect2.GetType()

, I always get Vector3

.

+3


source to share


4 answers


Although struct

, Vector3

implements Equals

through identity mapping. In other words, vect1

will only be equal vect2

if they are the same instance.

However does Vector3

implement ==

to test for value equality, so use that instead.



See https://msdn.microsoft.com/en-us/library/vstudio/ms128863%28v=vs.90%29.aspx for details .

+4


source


Vector3

overrides operator==

to "return true for vectors that are really close to equal". Since you may have some subtle differences in floating point values, you can try instead ==

:



vect1 == vect2

      

+1


source


That's why you could see what was happening

Vector3 v1 = new Vector3(150.001f, 150.002f, 150.003f);
Vector3 v2 = new Vector3(150.002f, 150.003f, 150.004f);
Debug.Log(v1);
Debug.Log(v2);
Debug.Log(v1 == v2);
Debug.Log(v1.Equals(v2));
Debug.Log(Vector3.Distance(v1, v2) > 1e-3f);

      

Will open

(150.0, 150.0, 150.0)

(150.0, 150.0, 150.0)

False

False

True

The problem is that your definition may be quite close enough to differ from unity. You can check it using this function

public static bool AlmostEqual(Vector3 v1, Vector3 v2, float tolerance)
{
    return Mathf.Abs(Vector3.Distance(v1, v2)) <= tolerance;
}

      

+1


source


Hi guys, I will tell you how I have solved the problem so far. I made a member to compare members.

int vect1x=(int)vect1.x;
int vect1y=(int)vect1.y;
int vect1z=(int)vect1.z;
int vect2x=(int)vect2.x;
int vect2y=(int)vect2.y;
int vect2z=(int)vect2.z;
Debug.Log((vect1x==vect2x)&&(vect1y==vect2y)&&(vect1z==vect2z));

      

I know it's verbose, but at least it works because it's a simple comparison between integers ...

-1


source







All Articles