- Home /
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;
Answer by CHPedersen · Feb 16, 2015 at 02:07 PM
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.
You're welcome. :) But please do modify that code to make it more robust. There are plenty of ways it can be slow or break. For example, it naively assumes A and B have the same size.
Answer by leventalpsal · Jul 10, 2017 at 08:08 AM
This is my checklist, my road to salvation :) ( successful changing the alpha transparency of a texture per pixel )
Standard shader render mode should be transparent or any other shader with transparency used
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
Texture must be read / write enabled
Texture format should be one of the formats that support alpha like RGBA 32 bit
Instantiating of the texture at runtime is needed in order to avoid modifying the original texture
Instantiating should be done once at the start.
The instantiated texture should be set as the materials texture.
Your answer
Follow this Question
Related Questions
alpha mapping on 3D objects 1 Answer
Texture Format missing? 0 Answers
use Alpha from image in Fragment shader 0 Answers
Movie GUI Texture Alpha? 1 Answer
How to move alpha mask along the floor plane as the user (camera) moves 1 Answer