Skip to content

Instantly share code, notes, and snippets.

@Iam1337
Last active October 19, 2015 17:45
Show Gist options
  • Save Iam1337/89ecd1d07b648777a2fc to your computer and use it in GitHub Desktop.
Save Iam1337/89ecd1d07b648777a2fc to your computer and use it in GitHub Desktop.
Screenshot сontroller for Unity3D.
// Vladimir Sigalkin (ExT)
using UnityEngine;
using System;
using System.IO;
public class ScreenshotController : MonoBehaviour
{
public KeyCode Key = KeyCode.A;
public int Width = 1920;
public int Height = 1080;
public Camera[] Cameras;
public string DefaultFolderPath = "./Screenshots/";
void Update()
{
if (Input.GetKeyDown(Key))
{
var fileName = ScreenshotName(DefaultFolderPath, Width, Height);
MakeScreenshot(fileName, Width, Height, Cameras);
}
}
public static void MakeScreenshot(string fileName, int width, int height, Camera[] cameras)
{
var renderTexture = new RenderTexture(width, height, 24);
var screenshotTexture = new Texture2D(width, height, TextureFormat.ARGB32, false);
foreach (var camera in cameras)
{
var tempRender = camera.targetTexture;
camera.targetTexture = renderTexture;
camera.Render();
RenderTexture.active = renderTexture;
screenshotTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
camera.targetTexture = tempRender;
RenderTexture.active = null;
Destroy(renderTexture);
}
File.WriteAllBytes(fileName, screenshotTexture.EncodeToPNG());
Debug.Log(string.Format("Screenshot saved: \"{0}\"", fileName));
Destroy(screenshotTexture);
}
public static string ScreenshotName(string path, int width, int height)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return string.Format("{0}{1}_{2}x{3}_{4}.png", path, Application.loadedLevelName, width, height, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment