Skip to content

Instantly share code, notes, and snippets.

@teebarjunk
Last active November 3, 2022 16:34
Show Gist options
  • Save teebarjunk/1e3e9e22dd8a5729575c4299caefc6af to your computer and use it in GitHub Desktop.
Save teebarjunk/1e3e9e22dd8a5729575c4299caefc6af to your computer and use it in GitHub Desktop.
Unity: Adds a context menu option to RenderTextures that allows saving them to a file.
public static class RenderTextureToFile
{
[UnityEditor.MenuItem("CONTEXT/RenderTexture/To Texture")]
static void SaveRenderTextureToTexture(UnityEditor.MenuCommand command)
{
var rt = (RenderTexture)command.context;
if (rt == null)
return;
// Ask for a save path.
var path = UnityEditor.EditorUtility.SaveFilePanel("Save RenderTexture...", Application.dataPath, rt.name, "png");
// Escape if user clicked cancel.
if (path == "")
return;
// Set RenderTexture to one that will be read.
RenderTexture.active = rt;
// Create Texture2D of same size.
// NOTE: If the TextureFormat of the Texture2D and the RenderTextureFormat of the RenderTexture aren't compatible, there will be an error. ARGB32 works for most cases though.
var tex = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tex.Apply();
// Set to null so the RenderTexture won't accidentally be drawn to somewhere else.
RenderTexture.active = null;
// Encode to PNG.
var bytes = tex.EncodeToPNG();
// Write to file.
System.IO.File.WriteAllBytes(path, bytes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment