Skip to content

Instantly share code, notes, and snippets.

@yasirkula
Last active March 27, 2020 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yasirkula/aed84983ac58c66c18387bc267f1acb5 to your computer and use it in GitHub Desktop.
Save yasirkula/aed84983ac58c66c18387bc267f1acb5 to your computer and use it in GitHub Desktop.
Quickly capture a screenshot in Unity
using System;
using System.IO;
using UnityEngine;
public static class ScreenshotCapture
{
// Saves the screenshot to desktop
public static void Capture()
{
string saveDirectory = Environment.GetFolderPath( Environment.SpecialFolder.DesktopDirectory );
int fileIndex = 0;
string path;
do
{
path = Path.Combine( saveDirectory, string.Format( "Screenshot {0}.jpeg", ++fileIndex ) );
} while( File.Exists( path ) );
Capture( path );
}
public static void Capture( string path )
{
Camera camera = Camera.main;
RenderTexture temp = RenderTexture.active;
RenderTexture temp2 = camera.targetTexture;
RenderTexture renderTex = RenderTexture.GetTemporary( Screen.width, Screen.height, 24 );
Texture2D screenshot = null;
try
{
RenderTexture.active = renderTex;
camera.targetTexture = renderTex;
camera.Render();
screenshot = new Texture2D( renderTex.width, renderTex.height, TextureFormat.RGB24, false );
screenshot.ReadPixels( new Rect( 0, 0, renderTex.width, renderTex.height ), 0, 0, false );
screenshot.Apply( false, false );
File.WriteAllBytes( path, screenshot.EncodeToJPG() );
}
finally
{
camera.targetTexture = temp2;
RenderTexture.active = temp;
RenderTexture.ReleaseTemporary( renderTex );
if( screenshot != null )
UnityEngine.Object.DestroyImmediate( screenshot );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment