Change alpha channel of a texture in code

Is there a possibility to change a textures alpha channel with code?

Texture2D colorImg;
Texture2D greyscaleImg;

colorImg.a = greyscaleImg.a;

A texture doesn’t have one value for alpha that spans the entire texture, instead, the alpha channel is per pixel.

To copy the alpha channel from one texture to another, you have to pass through the texture in its entirety, pixel by pixel, and copy each pixel’s alpha channel over. Here’s a function that demonstrates that approach:

private void TransferAlpha(Texture2D A, Texture2D B)
{
    Color pixA, pixB;

    for (int i = 0; i < A.width; i++)
    {
        for (int j = 0; j < A.height; j++)
        {
            // Read out pixel value at that location in both textures
            pixA = A.GetPixel(i,j);
            pixB = B.GetPixel(i,j);

            // Copy the alpha channel from B's pixel and assign it to A's pixel
            pixA.a = pixB.a;

            // Set the changed pixel back to A in that location
            A.SetPixel(i, j, pixA);
        }
    }

    // Apply the results
    A.Apply();
}

Notice that this is kind of slow and that there are better ways, such as reading out the whole pixel array and iterating over that, then using SetPixels to set the whole texture at a time. But this demonstrates the idea, at least.

This is my checklist, my road to salvation :slight_smile: ( successful changing the alpha transparency of a texture per pixel )

  1. Standard shader render mode should be transparent or any other shader with transparency used

  2. Materials texture alpha is different from textures per pixel alpha. Materials texture alpha should be 1 so that when texture per pixel alpha is more than 0 it can be visible

  3. Texture must be read / write enabled

  4. Texture format should be one of the formats that support alpha like RGBA 32 bit

  5. Instantiating of the texture at runtime is needed in order to avoid modifying the original texture

  6. Instantiating should be done once at the start.

  7. The instantiated texture should be set as the materials texture.