Unity – Saving GameObject Texture To Disk As PNG

I’m working on my space sim game that will be on STEAM. In the meantime before it’s released I’ve decided to post some tips I’ve learned over the years using Unity. I’ll post at least one tip a week.

This post will be on how to save the texture, or the main image part of the GameObject material, to disk using C#.

Looking at the Unity API documentation is the best way to find answers to questions as the documentation will show you how to correctly perform a task. The Unity team has gone through a lot of trouble to document the Unity game engine. They have even provided info on how to optimize games.

Below is example code for saving the mainTexture from a GameObject to the hard disk.

Texture2D tempTexture= gameObject.GetComponent<MeshRenderer>().sharedMaterial.mainTexture as Texture2D;

byte[] bytes = tempTexture.EncodeToPNG();

File.WriteAllBytes(path+ "saved_texture.png", bytes);

For this to work you will need the following in the Unity script:

Using System.IO;

The File.WriteAllBytes method is part of the System.IO namespace.

The ‘path’ in the last line of code is a string datatype that holds the folder location to save the png image to on the hard drive. This Unity Documentation page has useful info regarding that.

I hope you’ve found this useful.

🙂