Emirhan Yılmaz
Emirhan Yılmaz

Reputation: 86

Compare material color of object and background color

Hello I am trying to compare material color of object and background color.But it doesn't work in if statement.

void Update() {
        if(Input.GetMouseButtonDown(0)) {
            if(currentItem != null) {
                if(currentItem.CompareTag("Item")) {
                    print(currentItem.GetComponent<MeshRenderer>().material.color);
                    print(Camera.main.backgroundColor);
                    if(currentItem.GetComponent<MeshRenderer>().material.color == Camera.main.backgroundColor) {
                        Destroy(currentItem);
                        Camera.main.GetComponent<GameManager>().IncreaseScore();
                    } else {
                        Camera.main.GetComponent<GameManager>().GameOver();
                    }
                }
            }
        }
    }

When I try print colors they looks same but it returns false in if statement.

Upvotes: 1

Views: 53

Answers (1)

Iggy
Iggy

Reputation: 4888

There might be small differences as the Color object formats the components. Try printing each color component individually.

public static bool ColorEquals(Color a, Color b, float tolerance = 0.04f) 
{
    if (a.r > b.r + tolerance) return false;
    if (a.g > b.g + tolerance) return false;
    if (a.b > b.b + tolerance) return false;
    if (a.r < b.r - tolerance) return false;
    if (a.g < b.g - tolerance) return false;
    if (a.b < b.b - tolerance) return false;
 
    return true;
}

Upvotes: 1

Related Questions