Skip to content

Instantly share code, notes, and snippets.

@gemfile0
Created March 20, 2019 07:54
Show Gist options
  • Save gemfile0/057061eecda303ed722031a6a24e171c to your computer and use it in GitHub Desktop.
Save gemfile0/057061eecda303ed722031a6a24e171c to your computer and use it in GitHub Desktop.
Take a screenshot of the game window in unity editor.
using System;
using System.IO;
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class EditorScreenshot : MonoBehaviour
{
[SerializeField] string folder = "EditorScreenshot/results";
[SerializeField] string prefix = "screenshot";
[SerializeField] bool ensureTransparentBackground = false;
Camera Camera
{
get
{
if (camera == null) {
camera = GetComponent<Camera>();
}
return camera;
}
}
new Camera camera;
int Width
{
get => Camera.main.pixelWidth;
}
int Height
{
get => Camera.main.pixelHeight;
}
[ContextMenu("Take Screenshot")]
public void TakeScreenshot()
{
PrepareCamera();
WriteScreenshot();
}
void WriteScreenshot()
{
RenderTexture renderTextureBefore = RenderTexture.active;
RenderTexture.active = camera.targetTexture;
Debug.Log($"{Width}x{Height}");
Texture2D screenshot = new Texture2D(Width, Height, TextureFormat.ARGB32, false);
screenshot.ReadPixels(new Rect(0, 0, Width, Height), 0, 0, false);
if (QualitySettings.activeColorSpace == ColorSpace.Linear)
{
Color[] pixels = screenshot.GetPixels();
for (int p = 0; p < pixels.Length; p++)
{
pixels[p] = pixels[p].gamma;
}
screenshot.SetPixels(pixels);
}
screenshot.Apply(false);
folder = GetSafePath(folder.Trim('/'));
prefix = GetSafeFilename(prefix);
string dir = $"{Application.dataPath}/{folder}/";
string filename = $"{prefix}_{DateTime.Now.ToString("yyMMdd_HHmmss")}.png";
string path = $"{dir}{filename}";
Directory.CreateDirectory(dir);
File.WriteAllBytes(path, screenshot.EncodeToPNG());
camera.targetTexture = null;
RenderTexture.active = renderTextureBefore;
Debug.Log("Screenshot saved to:\n" + path);
}
void PrepareCamera()
{
Camera camera = Camera;
camera.targetTexture = new RenderTexture(Width, Height, 0, RenderTextureFormat.ARGB32);
CameraClearFlags clearFlagsBefore = camera.clearFlags;
Color backgroundColorBefore = camera.backgroundColor;
if (ensureTransparentBackground)
{
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = new Color();
}
camera.Render();
if (ensureTransparentBackground)
{
camera.clearFlags = clearFlagsBefore;
camera.backgroundColor = backgroundColorBefore;
}
}
public string GetSafePath(string path)
{
return string.Join("_", path.Split(Path.GetInvalidPathChars()));
}
public string GetSafeFilename(string filename)
{
return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment