CodingJar

Export Render Textures from Unity (Fixed)

Nov 20th, 2013
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using UnityEngine;
  2. using UnityEditor;
  3.  
  4. namespace CodingJar
  5. {
  6.     /**
  7.      * This class adds a menu item which allows you to save out a render texture to a PNG for proper inspection.
  8.      * It needs to go in an Editor/ folder.
  9.      */
  10.     public static class RenderTextureExporter
  11.     {
  12.         [MenuItem("Assets/Coding Jar/Save Render Texture", true)]
  13.         static bool ValidateSaveRenderTexture()
  14.         {
  15.             RenderTexture rt = Selection.activeObject as RenderTexture;
  16.             return ( rt != null );
  17.         }
  18.  
  19.         [MenuItem("Assets/Coding Jar/Save Render Texture")]
  20.         static void SaveRenderTexture()
  21.         {
  22.             RenderTexture rt = Selection.activeObject as RenderTexture;
  23.             if ( rt == null )
  24.             {
  25.                 EditorUtility.DisplayDialog( "Error", "You need to select a Render Texture", "OK" );
  26.                 return;
  27.             }
  28.  
  29.             string fileName = EditorUtility.SaveFilePanel( "Save As", "Assets/", Selection.activeObject.name, "png" );
  30.             if ( !string.IsNullOrEmpty(fileName) )
  31.             {
  32.                 var oldRT = RenderTexture.active;
  33.                 RenderTexture.active = rt;
  34.  
  35.                 Texture2D newTexture = new Texture2D( rt.width, rt.height, TextureFormat.ARGB32, false );
  36.                
  37.                 // Write out the results...
  38.                 newTexture.ReadPixels( new Rect(0.0f, 0.0f, rt.width, rt.height), 0, 0, false );
  39.                 newTexture.Apply(false, false);
  40.                 System.IO.File.WriteAllBytes( fileName, newTexture.EncodeToPNG() );
  41.  
  42.                 RenderTexture.active = oldRT;
  43.             }
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment