You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Unity的Color32数组中检测特定颜色?

解决Unity中Color32数组的颜色判断问题

嘿,我来帮你搞定这个Color32比较的麻烦!你遇到的问题主要是错误的字符串比较方式,还有代码里的小疏漏,咱们一步步来解决:

为什么原来的方法行不通?

  • 你写的string.Equals("RGBA(239, 239, 239, 255)")根本没传入要比较的color.ToString()结果,而且即使补上,Color32.ToString()的输出格式可能随Unity版本或设置变化(比如空格、括号格式),用字符串比较颜色非常不可靠。
  • 另外你在Start()里重新声明了Color32[] pix,这会覆盖类的成员变量pix,导致后续如果要在其他方法里调用这个数组会出问题。

正确的颜色判断方法

Color32的四个分量(r、g、b、a)都是byte类型,直接比较分量是最稳妥的方式,当然也可以直接比较Color32对象本身——Unity已经重载了它的相等运算符,用起来很方便。

方法1:逐个比较RGBA分量

这种方式最直观,完全不用担心格式问题:

using System;
using UnityEngine;

public class SpawnrateGrid : MonoBehaviour 
{
    public Texture2D sourceTex;
    Color32[] pix;
    int i = 1;

    void Start () 
    {
        // 直接给成员变量赋值,不要重新声明
        pix = sourceTex.GetPixels32();
        UnitySystemConsoleRedirector.Redirect();

        foreach (Color32 color in pix) 
        {
            Console.WriteLine("Pixel group {0} = {1}", i, color);
            
            // 逐个匹配RGBA分量
            if (color.r == 239 && color.g == 239 && color.b == 239 && color.a == 255)
            {
                // 这里写你要执行的逻辑
                Console.WriteLine("找到目标颜色啦!");
            }

            i++;
            if (i > 10)
            {
                break;
            }
        }
    }
}

方法2:创建目标Color32对象直接比较

如果你觉得逐个写分量麻烦,可以先创建一个目标Color32,然后直接用==或者Equals()比较:

void Start () 
{
    pix = sourceTex.GetPixels32();
    UnitySystemConsoleRedirector.Redirect();

    // 提前创建好目标颜色
    Color32 targetColor = new Color32(239, 239, 239, 255);

    foreach (Color32 color in pix) 
    {
        Console.WriteLine("Pixel group {0} = {1}", i, color);
        
        // 直接比较Color32对象
        if (color == targetColor)
        {
            Console.WriteLine("找到目标颜色啦!");
        }

        i++;
        if (i > 10)
        {
            break;
        }
    }
}

额外提示:按特定索引访问像素

如果需要定位到特定索引的像素(而不是遍历所有),可以用for循环代替foreach:

for (int index = 0; index < pix.Length; index++)
{
    Color32 color = pix[index];
    // 比如只检查第5个像素(索引从0开始)
    if (index == 4 && color == targetColor)
    {
        // 执行你的逻辑
        Console.WriteLine($"索引{index}处找到目标颜色!");
    }
}

这样就能准确判断Color32数组里的特定颜色啦!

内容的提问来源于stack exchange,提问作者Redshade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:09:29