Created
September 24, 2015 08:01
-
-
Save n-yoda/4bbb0e2f93cb918823a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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