nix86
nix86

Reputation: 3037

comparing two identical objects return false in Unity 3D (c#)

I am writing a C# script on Unity 3D. I have two Vector3 that are the same. When I do:

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

I get the same result (500.0, 150.0, 0.0). The problem is that when I do vect1.Equals(vect2) I get false! How is it possible?

P.S. I am sure that they are both Vector3 because when I do vect1.GetType() and vect2.GetType() I always get Vector3.

Upvotes: 5

Views: 2346

Answers (4)

nix86
nix86

Reputation: 3037

Hi guys I tell you how I solved the problem so far. I have made a member to member comparison.

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 that it's verbose but at least it works cause it's a simple comparison between integers...

Upvotes: -2

Colton White
Colton White

Reputation: 976

Here is why you could see what happens

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);

This will print out

(150.0, 150.0, 150.0)

(150.0, 150.0, 150.0)

False

False

True

The issue is that your definition of close enough may be different from unity's. You can check that by using this function

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

Upvotes: 1

D Stanley
D Stanley

Reputation: 152501

Vector3 overrides the == operator to "return true for vectors that are really close to being equal". Since you may have some imperceptible differences in your floating-point values you might try using == instead:

vect1 == vect2

Upvotes: 1

David Arno
David Arno

Reputation: 43254

Despite being a struct, Vector3 implements Equals via identity comparison. In other words, vect1 will only equal vect2 if they are the same instance.

However, Vector3 does 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.

Upvotes: 5

Related Questions