【问题标题】:Unity how to check for color matchunity如何检查颜色匹配
【发布时间】:2017-01-13 23:08:48
【问题描述】:

我正在使用 Unity 5,并且想检查两个游戏对象材质是否具有相同的匹配颜色并在颜色不匹配时采取措施。我正在使用下面的 c# 代码:

void OnCollisionEnter2D(Collision2D col)
{

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

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

【问题讨论】:

  • 您是否尝试过分别比较每个组件(rgba 或 xyzw)?这很痛苦,但很有效。
  • 它失败的原因是因为您不是在比较两种颜色,而是比较两个 Color 对象是否相等(即使它们具有相同的值,它们也很可能不是)。如果您想比较颜色,则必须比较每个单独的组件(r、g、b 甚至可能是 alpha),如果它们具有相同的值(转换为 Vector4 并且比较也可能有效)

标签: c# unity3d colors


【解决方案1】:

尝试将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);
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 2018-05-13
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多