Skip to content

Instantly share code, notes, and snippets.

@Noxalus
Created January 9, 2019 09:23
Show Gist options
  • Save Noxalus/c10a69da3131e1e78757f2be1f5e7f16 to your computer and use it in GitHub Desktop.
Save Noxalus/c10a69da3131e1e78757f2be1f5e7f16 to your computer and use it in GitHub Desktop.
Unity component to take a screenshot of the camera rendering
using System.IO;
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class CameraScreenshot : MonoBehaviour
{
[SerializeField] private RenderTexture _outputTexture = null;
[SerializeField] private KeyCode _key = KeyCode.Space;
[SerializeField] private string _path = string.Empty;
private Camera _camera;
private void Awake()
{
_camera = GetComponent<Camera>();
}
private void Update()
{
if (Input.GetKeyDown(_key))
{
_camera.forceIntoRenderTexture = true;
_camera.targetTexture = _outputTexture;
_camera.Render();
_camera.forceIntoRenderTexture = false;
_camera.targetTexture = null;
Texture2D texture = new Texture2D(_outputTexture.width, _outputTexture.height, TextureFormat.ARGB32, false);
RenderTexture.active = _outputTexture;
texture.ReadPixels(new Rect(0, 0, _outputTexture.width, _outputTexture.height), 0, 0);
RenderTexture.active = null;
File.WriteAllBytes(Path.Combine(_path, "Screenshot.png"), texture.EncodeToPNG());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment