Unity如何检查颜色匹配

时间:2016-09-06 13:12:11

标签: c# unity3d colors

我正在使用Unity 5并希望检查碰撞是否有两个游戏对象材料具有相同的匹配颜色,并且如果颜色不匹配则采取行动。我正在使用下面的c#代码:

void OnCollisionEnter2D(Collision2D col)
{

    if(col.gameObject.GetComponent<Renderer> ().material.color != this.gameObject.GetComponent<Renderer> ().material.color)
    {
        Destroy(col.gameObject);
    } 
}

这似乎不能正常工作,因为即使颜色匹配,游戏对象有时也会被破坏。只是想知道是否有另一种检查颜色匹配的方法?

1 个答案:

答案 0 :(得分:2)

尝试将color个对象保存在新的临时变量中,然后进行比较:

void OnCollisionEnter2D(Collision2D col)
{
    Color myColor = GetComponent<Renderer> ().material.color;
    Color otherColor = col.gameObject.GetComponent<Renderer> ().material.color;
    if(myColor.Equals(otherColor))
    {
        Destroy(col.gameObject);
    } 
}

如果这不起作用:

color编写扩展方法并像这样使用它:

分机类:

static class Extension
{
    public static bool IsEqualTo(this Color me, Color other)
    {
        return me.r == other.r && me.g == other.g && me.b == other.b && me.a == other.a;
    }
}

用法:

void OnCollisionEnter2D(Collision2D col)
{
    Color myColor = GetComponent<Renderer> ().material.color;
    Color otherColor = col.gameObject.GetComponent<Renderer> ().material.color;
    if(myColor.IsEqualTo(otherColor))
    {
        Destroy(col.gameObject);
    } 
}