GetPixel Not returning the same value after SetPixel.

Hello All,

I’m currently working on a Terraria clone to improve my programming skills. I’ve come to generating a map and decided to use a Texture2D to hold a map, using color coded pixels to represent the blocks at each position. However when I reach the point of getting the colors to place blocks, Instead of getting the color I have set, I get a slightly different shade of the color. For example. In my code I set the default color of a pixel to black. If I then ask to get the color of the pixel, instead of returning (0, 0, 0, 255) I get (1.000, 0.000, 1.000, 1.000) or (0.000, 1.000, 1.000, 1.000) and even sometimes (1.000, 1.000, 0.000, 1.000) but never (0, 0, 0, 255) which is what I’d expect.

I’ve don’t have my code with me as I’m not currently at home, but it went something like this:

// On Generating the map, I used an algorithm to generate hills etc but thats not needed here:
public void Generate()
{
Texture2D map = new Texture2D(width, height);

for(int i=0; i<width;i++){
for(int j=0;j<height;j++){

if ( j < width/2 ) 
{
    map.SetPixel(i, j, Color.green);
}
else
{
    map.SetPixel(i, j, Color.Black);
}

}}

map.Apply();
SetSpawnPoint();

}

// This is where it always went wrong since it would place the spawn right at the top of the map. suggesting that the very top most pixel was not black.
public void SetSpawnPoint()
{
int xPos = Mathf.RoundToInt( Random.Range(width/4, 3*width/4));

for(int j=0;j<height;j++)
{
    if( map.GetPixel(xPos, j) != Color.black )
    {
        map.SetPixel(xPos, j-1, Color.cyan);
        map.Apply();
        break;
    }
}

}

It was almost as if Unity is applying some form of antialiasing to the Texture even though it wasn’t being displayed anywhere. I did also try using Debug to have it print out the color it found and what it was comparing it with, but that also didn’t work.

From my searches on google, I found that most people with a similar problem were having issue with textures they had imported, but I’m not importing. Their issue was with the compression system used by unity, however Since I’m generating this texture, I shouldn’t be having these problems right?

I’d appreciate a quick response and I’ll add more detail if needed.

Kind Regards,
John

Please post your solutions as an actual answer so others can reference this in the search indexes. Thank you


In the Unity ‘Color’ struct, values for r, g, b, a are in the range of 0.0 to 1.0. There is a ‘Color32’ which has more traditional values in the range of 0 to 255. Setting pixels individually using GetPixels() and SetPixels() is expensive. Look at GetPixels()/SetPixels() (or better yet GetPixels32()/SetPixels32()), to get and set all the pixels rather than deal a function call for each pixel.

robertbu
1 day ago