Skip to content

Instantly share code, notes, and snippets.

@Nordaj
Last active June 18, 2017 22:26
Show Gist options
  • Save Nordaj/5fc8680c036ec65c4d4624f36e9bc1de to your computer and use it in GitHub Desktop.
Save Nordaj/5fc8680c036ec65c4d4624f36e9bc1de to your computer and use it in GitHub Desktop.
With this Unity editor script you can render the camera to an image at any resolution in engine. Should auto fill to be quick and easy. Just throw this in a folder named "Editor" under any directory in the project. To use go to Window/Render Camera. Enjoy
using System;
using System.IO;
using UnityEngine;
using UnityEditor;
public class RenderCamera : EditorWindow
{
//Private Variables
private Camera cam;
private Vector2 size;
private string dir;
private string texName;
[MenuItem("Window/Render Camera")]
static void Start()
{
RenderCamera win = (RenderCamera)EditorWindow.GetWindow(typeof(RenderCamera));
win.Show();
win.First();
}
public void First()
{
try
{
cam = GameObject.Find("Main Camera").GetComponent<Camera>();
}
catch { }
size = new Vector2(1920, 1080);
dir = "Screenshots/";
texName = "Render";
}
void OnGUI()
{
#region Options
cam = (Camera)EditorGUILayout.ObjectField("Camera", cam, typeof(Camera), true);
size = EditorGUILayout.Vector2Field("Size", size);
//Alot of code for that single line of input but it needed to be done...
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Directory");
Color temp = GUI.color;
GUI.color = new Color(temp.r, temp.g, temp.b, 0.5f);
GUILayout.Label("Assets/");
GUI.color = temp;
dir = EditorGUILayout.TextField(dir);
texName = EditorGUILayout.TextField(texName);
GUI.color = new Color(temp.r, temp.g, temp.b, 0.5f);
GUILayout.Label(".png");
GUI.color = temp;
EditorGUILayout.EndHorizontal();
#endregion
#region Render
if (GUILayout.Button("Render"))
{
//Create Stuff
RenderTexture rt = new RenderTexture(Convert.ToInt32(size.x), Convert.ToInt32(size.y), 0);
Texture2D tex = new Texture2D(rt.width, rt.height);
//Snap
cam.targetTexture = rt;
cam.Render();
//Read
RenderTexture.active = rt;
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tex.Apply();
//Clean Up
cam.targetTexture = null;
RenderTexture.active = null;
//Save To File
byte[] b = tex.EncodeToPNG();
File.WriteAllBytes(Application.dataPath + "/" + dir + texName + ".png", b);
}
#endregion
#region Help
EditorGUILayout.HelpBox("16:9:\n1080p: 1920x1080\n1440p: 2560x1440\n4k: 3840x2160\n\n21:9:\n1080p: 3440x1080\n1440p: 2560x1440\n4k: 5120x2160", MessageType.None);
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment