Skip to content

Instantly share code, notes, and snippets.

@hman278
Created February 2, 2024 13:28
Show Gist options
  • Save hman278/b3c7640d8e73813ec28a83f83c82745d to your computer and use it in GitHub Desktop.
Save hman278/b3c7640d8e73813ec28a83f83c82745d to your computer and use it in GitHub Desktop.
Take a screenshot using a specified camera in-game in Unity
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using Directory = UnityEngine.Windows.Directory;
public class ScreenshotTool : MonoBehaviour
{
[SerializeField] private Camera _targetCamera;
[SerializeField] private Vector2Int _targetResolution = new Vector2Int(1000, 1000);
private enum Filetype
{
JPG,
PNG,
TGA
}
[SerializeField] private Filetype _filetype;
[SerializeField] private string _screenshotName;
private void Start()
{
TakeScreenshot();
}
private void TakeScreenshot()
{
RenderTexture renderTexture = new RenderTexture(_targetResolution.x, _targetResolution.y, 24);
_targetCamera.targetTexture = renderTexture;
Texture2D screenShot = new Texture2D(_targetResolution.x, _targetResolution.y, TextureFormat.RGB24, false);
_targetCamera.Render();
RenderTexture.active = renderTexture;
screenShot.ReadPixels(new Rect(0, 0, _targetResolution.x, _targetResolution.y), 0, 0);
_targetCamera.targetTexture = null;
RenderTexture.active = null;
Destroy(renderTexture);
byte[] bytes = EncodeScreenshot(screenShot);
string screenshotPath = $"{Application.dataPath}/Screenshots";
if (!Directory.Exists(screenshotPath))
{
Directory.CreateDirectory(screenshotPath);
}
string path = $"{screenshotPath}/{_screenshotName}.{GetScreenshotFormat()}";
File.WriteAllBytes(path, bytes);
Debug.Log($"Took screenshot to: {path}");
}
private byte[] EncodeScreenshot(Texture2D screenShot)
{
List<byte> bytes = new List<byte>();
switch (_filetype)
{
case (Filetype.JPG):
bytes = screenShot.EncodeToJPG().ToList();
break;
case (Filetype.PNG):
bytes = screenShot.EncodeToPNG().ToList();
break;
case (Filetype.TGA):
bytes = screenShot.EncodeToTGA().ToList();
break;
}
return bytes.ToArray();
}
private string GetScreenshotFormat()
{
string format = "";
switch (_filetype)
{
case (Filetype.JPG):
format = "jpg";
break;
case (Filetype.PNG):
format = "png";
break;
case (Filetype.TGA):
format = "tga";
break;
}
return format;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment