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.

2 Answers

2

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 *= 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 = (Color32) fillColor; } tex2D.SetPixels32(fillPixels); return tex2D; }

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.