Skip to content

Instantly share code, notes, and snippets.

@n-yoda
Created September 24, 2015 08:01
Show Gist options
  • Save n-yoda/4bbb0e2f93cb918823a0 to your computer and use it in GitHub Desktop.
Save n-yoda/4bbb0e2f93cb918823a0 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEditor;
using System.IO;
public class BakeRenderTexture
{
[MenuItem("Assets/Bake RenderTexture to PNG")]
static void Bake()
{
// Get selected RenderTexture
RenderTexture rt = Selection.activeObject as RenderTexture;
if (!rt) return;
// Backup current state
RenderTexture backup = RenderTexture.active;
// Allocate CPU memory
var texture = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
// Read from GPU memory to CPU memory
RenderTexture.active = rt;
texture.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
// Save
var path = AssetDatabase.GenerateUniqueAssetPath(Path.ChangeExtension(AssetDatabase.GetAssetPath(rt), "png"));
File.WriteAllBytes(path, texture.EncodeToPNG());
// Free CPU memory
Object.DestroyImmediate(texture);
// Restore state
RenderTexture.active = backup;
// Refresh
AssetDatabase.Refresh();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment