Skip to content

Instantly share code, notes, and snippets.

@somedeveloper00
Created May 7, 2023 07:42
Show Gist options
  • Select an option

  • Save somedeveloper00/1717e721718c82fdf1ab79fab52715b2 to your computer and use it in GitHub Desktop.

Select an option

Save somedeveloper00/1717e721718c82fdf1ab79fab52715b2 to your computer and use it in GitHub Desktop.
Unity GameView Camera Render To PNG (editor-only)
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[RequireComponent( typeof(Camera) )]
public class GameViewRender : MonoBehaviour {
public int width = 1920;
public int height = 1080;
public int depth = 24;
public void Render() {
// create a rendertexture with the given dimentions
var rt = new RenderTexture( width, height, depth );
// set the rendertexture as the target texture for the camera
var camera = GetComponent<Camera>();
camera.targetTexture = rt;
camera.Render();
// open save file dialogue and get path
var path = EditorUtility.SaveFilePanel( "Save Rendered Image", "", "rendered", "png" );
// read the pixels from the rendertexture
var pixels = new Texture2D( width, height );
RenderTexture.active = rt;
pixels.ReadPixels( new Rect( 0, 0, width, height ), 0, 0 );
pixels.Apply();
// write the pixels to the file
var bytes = pixels.EncodeToPNG();
System.IO.File.WriteAllBytes( path, bytes );
// clean up
RenderTexture.active = null;
camera.targetTexture = null;
DestroyImmediate( rt );
Debug.Log( "Rendered image saved to " + path );
}
[CustomEditor( typeof(GameViewRender) )]
class editor : Editor {
public override void OnInspectorGUI() {
serializedObject.Update();
EditorGUILayout.PropertyField( serializedObject.FindProperty( nameof(width) ) );
EditorGUILayout.PropertyField( serializedObject.FindProperty( nameof(height) ) );
EditorGUILayout.PropertyField( serializedObject.FindProperty( nameof(depth) ) );
if (GUILayout.Button( "Render", GUILayout.Height( 30 ) )) {
( (GameViewRender)target ).Render();
}
serializedObject.ApplyModifiedProperties();
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment