C# 比较对象的材质颜色和背景颜色

C# 比较对象的材质颜色和背景颜色,c#,unity3d,C#,Unity3d,您好,我正在尝试比较对象的材质颜色和背景颜色。但它在if语句中不起作用 void Update() { if(Input.GetMouseButtonDown(0)) { if(currentItem != null) { if(currentItem.CompareTag("Item")) { print(currentItem.GetComponent<M

您好,我正在尝试比较对象的材质颜色和背景颜色。但它在if语句中不起作用

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();
                    }
                }
            }
        }
    }
void Update(){
if(Input.GetMouseButtonDown(0)){
如果(currentItem!=null){
if(currentItem.CompareTag(“项目”)){
打印(currentItem.GetComponent().material.color);
打印(摄像头、主屏幕、背景色);
if(currentItem.GetComponent().material.color==Camera.main.backgroundColor){
销毁(当前项);
Camera.main.GetComponent().IncreaseScore();
}否则{
Camera.main.GetComponent().GameOver();
}
}
}
}
}

当我尝试打印颜色时,它们看起来是一样的,但在if语句中返回false。

当颜色对象格式化组件时,可能会有一些小的差异。
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();
                    }
                }
            }
        }
    }
尝试单独打印每个颜色组件

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;
}
public static bool ColorEquals(颜色a、颜色b、浮动公差=0.04f)
{
如果(a.r>b.r+公差)返回false;
如果(a.g>b.g+公差)返回false;
如果(a.b>b.b+公差)返回false;
如果(a.r
是的,你是对的,有些组件是不同的。那么我如何解决这个问题才能在if语句中工作呢?@codemir我已经更新了答案。