Why are my pixels blurred? Strange antialiasing?

I am creating a texture in code, and setting the values. For some reason, I don’t know, the pixels drawn are blurred. What is going on?

    public Texture2D texture;


    Color32[] outputPixels;

    void Start()
    {
        texture = new Texture2D(320, 240, TextureFormat.ARGB32, false);
        texture.wrapMode = TextureWrapMode.Clamp;
	    texture.filterMode = FilterMode.Point;
	    texture.anisoLevel = 1;
	    texture.mipMapBias = -.5f;
        renderer.material.mainTexture = texture;
        outputPixels = new Color32[320*240];
        for (int y = 240 - 1; y >= 0; --y)
	    {
            int outputIndex = y * 320;
            for (int x = 0; x < 320; ++x, srcIndex ++, ++outputIndex)
	        {
                  // set every 8th column white, otherwise black
		      outputPixels[outputIndex] = ((x & 7) == 7) ? Color.white : Color.black;
		      outputPixels[outputIndex].a = 1;
            }
        }
        texture.SetPixels32(outputPixels);
        texture.Apply();
    }

I expect sharp white vertical lines every 8 pixels. I get grayness. Like antialiasing, but I don’t know now to disable that??? Texture is applied to material with standard scale and offset. Could it have something to do with it not being power-of-two sized?

UPDATE: It does seem to be related to power-of-two. I changed it to 512x256 and the lines are sharp. HOWEVER this does not solve my problem, I need a non-power-of-two size!!

The short answer is you can’t prevent the resampling at runtime and the only solution is to use power of two textures.

We had this question a couple of times. Basically Non Power of Two textures are only used in the GUI system and only when imported in the Unity editor. The importer will actually create two versions of the texture (when the importer is set to GUI).Both textures are created as the next larger power of two texture. However the “normal” texture is resampled to the new texture size and the GUI-version is just padded with empty space.

The support of those padded GUI textures is only internal. There’s no way (up to the current date) to create such a texture at runtime. Therefore: your only options are:

  • Don’t create the texture in code and don’t load it manually at runtime. (Of course only for GUI stuff. Any other use is still power of two resampled)
  • For GUI use, pad the texture yourself to the next power of two and handle the padding yourself. You can use GUI.DrawTextureWithTexCoords to handle the padding.
  • For any other use, you might just pad it the same way and adjust the texture coordinates

For more insight see this post by Aras.