- Home /
Creating Texture2D with alpha
I am creating a simple texture with green thick line by the following code:
Texture2D tex = new Texture2D (256, 256, TextureFormat.ARGB32, false);
for(int i=0; i<100; i++){
for(int j=0; j<15; j++){
tex.SetPixel(i, j, Color.green);
}
}
tex.Apply();
When I am using it I want that remaining pixels would be completely transparent. However, they are grey coloured. How could I change alpha values that pixels would get transparent.
Answer by Yword · Oct 20, 2014 at 04:08 AM
I think you need to fill the pixels with transparent color first.
Texture2D tex = new Texture2D (256, 256, TextureFormat.ARGB32, false);
Color fillColor = Color.clear;
Color[] fillPixels = new Color[tex.width * tex.height];
for (int i = 0; i < fillPixels.Length; i++)
{
fillPixels[i] = fillColor;
}
tex.SetPixels(fillPixels);
for(int i=0; i<100; i++)
{
for(int j=0; j<15; j++)
{
tex.SetPixel(i, j, Color.green);
}
}
tex.Apply();
Thanks, that's wonderful. I didn't knew that transparency is property of color.
My proposal as a static class
public static Texture2D FillColorAlpha(Texture2D tex2D, Color32? fillColor = null)
{
if (fillColor ==null)
{
fillColor = Color.clear;
}
Color32[] fillPixels = new Color32[tex2D.width * tex2D.height];
for (int i = 0; i < fillPixels.Length; i++)
{
fillPixels[i] = (Color32) fillColor;
}
tex2D.SetPixels32(fillPixels);
return tex2D;
}
Answer by bitCulture · May 31, 2018 at 06:03 PM
I know this is a super old post, but I am having the same problem even after pre-filling a Texture2D with completely transparent (and black) pixels. I was also sure to specify the TextureFormat (in this case as RGBA32 as I will be adding pixel data to it later from other textures in that format). At this point though, it's just a generic Texture2D with completely transparent pixel data and it's rendering as semi-transparent white.
Your answer
![](https://koobas.hobune.stream/wayback/20220613165447im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
SetPixels32 called with invalid number if pixels in the array 0 Answers
How to not see white background on texture 1 Answer
Unity changes pixel colors 2 Answers
Texture Compression format for UWP,Texture 0 Answers
Blending two Texture2D 1 Answer