- Home /
2D Texture EncodeToPNG not working as expected
So my script creates a texture from a color map I've created using perlin noise. This texture is my game map. I'm wanting to save the texture as a PNG for later use. My code works for saving the PNG and I can even add the PNG onto the material but it doesn't show the texture when viewing the material in the inspector.
When I try to open the PNG from the file explorer or in the Unity file explorer to see my "game map", it's completely blank even though I can attach it to a material and see it in game. I'm assuming this is because the byte data is still there for Unity to read and display in the editor, but I'm not sure what's missing for the PNG to actually be viewable via the inspector or from a desktop image viewer.
Texture Creation:
public static Texture2D TextureFromColorMap(Color[] colorMap, int width, int height) {
Texture2D texture = new Texture2D(width, height);
texture.filterMode = FilterMode.Point;
texture.wrapMode = TextureWrapMode.Clamp;
texture.SetPixels(colorMap);
texture.Apply();
return texture;
}
Below method would be called like so: DrawTexture(TextureFromColorMap(colorMap, width, height), true);
Drawing texture and saving if desired:
public Renderer textureRender;
public void DrawTexture(Texture2D texture, bool saveTexture) {
textureRender.sharedMaterial.mainTexture = texture;
textureRender.transform.localScale = new Vector3(texture.width * 0.001f, 1, texture.height *
0.001f);
if (saveTexture) {
var bytes = texture.EncodeToPNG();
var dirPathToSave = Application.dataPath + "/Sprites/Maps/";
string timeStamp = DateTime.Now.ToString("yyyyMMdd-HHmmssff");
if (Directory.Exists(dirPathToSave)) {
File.WriteAllBytes(dirPathToSave + "Map-Texture-" + timeStamp + ".png", bytes);
} else {
Directory.CreateDirectory(dirPathToSave);
}
}
}
Thanks for any help in advance.
So, it has something to do with Alpha Source. If I change the Alpha Source to "None", I can see the map in the inspector. However, the image is still completely transparent when viewing in an image viewer.
Answer by Bunny83 · Jan 20 at 07:51 PM
Well, where do your colors come from? A Color value represents an RGBA value. So what is "a" set to? Is it possible that all your color values have an alpha value of 0? We don't know what it is since your "TextureFromColorMap" method just takes a Color array and we don't know where it comes from.
That's exactly it which makes sense as to why changing alpha transparency on the texture would then show the texture in the Unity file explorer. Attached is more information about my "regions" that contain the color arrays which are used with relation to the noise map.