Question

What I want to do is loop through the picture checking for pixels of specific color and count them. This is cruical for my project.

So the problem is that comparing GetPixel to Color never returns true even if the colors are the same.

I tested it with a single color square texture and I Debug-Logged the value of GetPixel and it was: "RGB(0.098,0.451,0.000,1.00)", which was the color I was looking for, but it still returned false.

Also I'm using JavaScript in Unity (UnityScript) and I have no errors. RGB values are in percentages and yes I enabled reading on texture.

Here is the code, please help me.

#pragma strict

public static function PixelMagic()
{   
var slika:Texture2D = Resources.Load("backgr",Texture2D);
var pixel_color:Color = new Color(0f,0f,0f,0f);
var green:Color = new Color(0.098f,0.451f,0f,1f);
var hit = 0;

for(var x=0; x<slika.width; x++)
{
    for(var y=0; y<slika.height; y++)
    {
        pixel_color = slika.GetPixel(x,y);

        if(green==pixel_color)
        {
            hit++;
        }
    }   
}
Debug.Log(hit);
Debug.Log(pixel_color);
}
Was it helpful?

Solution

I see 2 potential problems:

1 - You are probably having problem because they are two different objects (with the same value). Take a look at this to know more about objects comparison in JavaScript.

The quickest/easiest fix would be to just compare their values instead of the color.

2 - You should make sure the green color you are getting from the texture is "pure", that is, it's (0.098f,0.451f,0f,1f) and not (0.09800001f,0.451f,0f,1f).

It's dangerous to compare floats, for example 1.0f == 10f/10f might not return true. You can use Unity's Mathf.Approximately() to make these comparisons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top