Storing information in a texture and sending it to a shader - problem in retreiving values

I store some information in a dynamically created texture. It holds a number (0-255) in the rgb channels for each cell I have. I checked in photoshop and the values are the way they should be for each pixel.

The way i store information in is as follows in Unity:

byte r = (myMesh.info0);
byte g = (myMesh.info1);
byte b = (myMesh.info2);

meshInfoTexture.SetPixel(iTextureX, iTextureY, new Color32(r,g,b, 255));

In my shader i get the color of the pixel by tex2D, and then I try to get that value back to the range of 0-255:

float4 myPixelColor = tex2D(_InfoTexture, pixelPos / 64);
int iInfoValue = (int)(myPixelColor.b*255.0f);

However these never end up in the value ranges they were supposed to. How can I get the values back? I know the position in the texture is calculated correctly 100%, and also the values in photoshop are the way they should be (rgb numbers). I tried flooring the value, experimenting with some math, but it never works, it goes back to 0 or gets these numbers all over the place. Does this have to do with the precision of floats? Or am i missing something really simple?

Some possible problems:

  • first make sure your texture is not in a compressed format that might cause data loss.
  • Make sure you disable MipMaps (or not generating them).
  • Make sure that it is either a power of two texture or set it as non-power-of-two.
  • Make sure you set the texture filtering to point and not bilinear or trilinear.
  • casting a float to int might result in a value one off. That’s because 3.0 might come out as 2.99999. The usual solution is to simply add “0.5f” before you cast it to int. This does only work for positive numbers. So 2.9999 + 0.5 → 3.4999 → 3

Also keep in mind that textures contain discrete values while the UV space is a continuous space. Pixels have a width and height. For example a 2x2 texture a U value of “0” would reference the left edge of the left pixel column while “1” would reference the right edge of the right pixel. 0.50001 is the left edge of the right pixel and 0.49999 is the right edge of the left pixel.

So usually when you have an image with a resolution of 64x64 you would add 0.5 to your desired pixel position and divide by “64” to sample the center of each pixel. Of course your pixel position is in range “0-63”