- Home /
nor detecting the pixel of a given color
I am trying to find the grey pixels in an image. The image has exactly 6 of them. the image is here
This is my code.
void GetPlayerSpawnPoints ( Texture2D imageMap )
{
Color PlayerColor = new Color(0.5f, 0.5f, 0.5f, 1f);
for ( int x = 0; x < imageMap.width; x++ )
{
for ( int y = 0; y < imageMap.height; y++ )
{
//GetSpawnPoints ( x, y, imageMap );
Color pixelColor = imageMap.GetPixel(x, y);
// is the pixel grey?
if ( pixelColor == PlayerColor )
{
playerSpawnPoints.Add ( new PlayerSpawnData ( x + ( mapOffsetX * imageMap.width ), y + ( mapOffsetY * imageMap.height ) ) );
Debug.Log ( "FOUND" );
}
}
}
}
For some reason, the code does not find the grey pixel but it does find the black and the blue ones. Can someone help, please.
Answer by Pangamini · Jun 26, 2019 at 08:06 AM
Well, colors in your texture are most likely stored in Color32 format (most commonly not true for HDR textures or some special formats). So GetPixel() does a conversion from byte to float, which quite possibly means that your color channel is never exactly 0.5f. Basically, hoping that two floats whose values have different origins (are not a copy of each other) is always naive. You could include some value tolerance, compare Color32 instead of color (using GetPixel32() ) etc
When I use Color32 I can't use the x, y coordinates of the tile. I am doing this another way. Thanks for your response.
What does it have to do with tiles? Just ins$$anonymous$$d of texture.GetPixel(), use texture.GetPixel32() And of course, change variable type from Color to Color32
@Panga$$anonymous$$i, I changed the code on your advice to void GetSpawnPoints ( Texture2D image$$anonymous$$ap ) { Color PlayerColor = new Color(1, 1, 0, 1);
for ( int x = 0; x < image$$anonymous$$ap.width; x++ )
{
for ( int y = 0; y < image$$anonymous$$ap.height; y++ )
{
//GetSpawnPoints ( x, y, image$$anonymous$$ap );
Color32 pixelColor = image$$anonymous$$ap.GetPixel(x, y);
Debug.Log ( pixelColor );
// is the pixel yellow?
if ( pixelColor == PlayerColor )
{
Debug.Log ( pixelColor );
playerSpawnPoints.Add ( new PlayerSpawnData ( x + ( mapOffsetX * image$$anonymous$$ap.width ), y + ( mapOffsetY * image$$anonymous$$ap.height ) ) );
Debug.Log ( "FOUND" );
}
}
}
}
Now it works. Thank you.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Collision Not Working 1 Answer
get_version can only be called from the main thread. 0 Answers