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.