- Home /
Check if every pixel of a texture is transparent
Hello
I am currently trying to check if a texture is fully transparent. Basically, check if there's absolutely nothing on the texture. I am generating these textures at runtime and it can happen that there's nothing on the texture because of the lack of renderers on an object, and if there's nothing there, I want to take care of it in some other way. But I don't have any idea how I could check every pixel of a texture to see if it's 100% transparent.
Any help with this would be greatly appreciated!
Thanks
Answer by AurimasBlazulionis · Mar 05, 2017 at 10:58 AM
just do a for loop:
bool IsTransparent(Texture2D tex) {
for (int x = 0; x < tex.width; x++)
for (int y = 0; y < tex.height; y++)
if (tex.GetPixel(x, y).a != 0)
return false;
return true;
}
If you also need to check if all color values are 0, then just change the if statement to if (tex.GetPixel(x, y).Equals(new Color(0,0,0,0)))
. Sure, you could define the color 0 0 0 0 as a variable and use it so no stack/heap allocation occurs.
Thank you for your help! It worked perfectly! I honestly didn't have a clue about GetPixel. I must have missed it both while testing in Unity and when checking the docs. :S
Ins$$anonymous$$d of calling GetPixel in a nested for loop, call GetPixels or GetPixels32 before the loop and reference that array of pixels for better performance.
It does not only increase the performance dramatically but also simplifies the iteration since you just have one big array you have to deal with. I'm even wondering since he's generating the texture at runtime he should already have such an array when generating the texture.
Your answer
Follow this Question
Related Questions
Shader alpha value consistent with all transparent objects 0 Answers
Transparent terrain shader not working 2 Answers
Stencil buffer and transparency 0 Answers
Change Alpha on individual Texture2Ds 1 Answer
Slowly fades from opaque to alpha 2 Answers