Comparing 2 color variables.

Hi there, I’m trying to compare 2 colour variables but having no success.

Setting them like this:

private var colour1 : Color = new Color(1.000, 0.945, 0.000, 1.000);
// uvPoint refers to a conversion from a RaycastHit2D's point to uv coordinates
private var colour2 : Color = theSprite.texture.GetPixel(uVPoint.x, uVPoint.y);

And comparing like this:

// This happens on clicking on the colour.

if (colour1 == colour2)
{
   print("colour1 = colour2");
   print("colour1 = "+ colour1);
   print("colour2 = "+ colour2);
}

else if (colour1 != colour2)
{
   print("colour1 != colour2");
   print("colour1 = "+ colour1);
   print("colour2 = "+ colour2);
}

I keep getting the results:

colour1 != colour2

colour1 = RGBA(1.000, 0.949, 0.000, 1.000)

colour2 = RGBA(1.000, 0.949, 0.000, 1.000)

So if both colour variables have identical contents am I missing something fundamental about how colors should be compared?

The sprite texture is set to RGBA 32 bit, if that helps anything…

Thanks very much!

UPDATE:

Tried to print each individual colour value, which gives fuller results. Here’s the culprit:

colour1.g = 0.9490196

colour2.g = 0.949

Am now wondering if using Color32 would solve this issue or if it would have the same issue? (Looking into it and will post an answer soon)

I would recommend to separately compare the r, g, b and a variables (respectively only the ones you need).

Also try printing the values of colour2 separately (eg. "print(colour2.r + ", " + colour2.g + ", " + colour2.b + “, " + colour2.a)”) and check if they are REALLY equal to colour1. Unity logs often skip decimals.

You could also try out the following:

if(colour1.Equals(colour2))
{
	// Do stuff
}

(but I don’t know if this is actually the same as the == operator)

UPDATE:

As I said, Unity log often skips decimals.
To compare those values up to 3 decimals you could do the following:

if((int)(colour1.r * 1000) == (int)(colour2.r * 1000))
{
    // Do stuff
}