Skip to content

Instantly share code, notes, and snippets.

@samloeschen
Last active July 9, 2020 16:19
Show Gist options
  • Select an option

  • Save samloeschen/5441a4bea804486496ebf417d9a31f1a to your computer and use it in GitHub Desktop.

Select an option

Save samloeschen/5441a4bea804486496ebf417d9a31f1a to your computer and use it in GitHub Desktop.
DelayedCameraCapture
using System;
using System.IO;
using System.Collections;
using UnityEngine;
public class DelayedCaptureBehaviour: MonoBehaviour {
public new Camera camera;
public int delayFrames;
public KeyCode targetKey;
bool _capturing;
void OnEnable() {
_capturing = false;
}
void Update() {
if (Input.GetKeyDown(targetKey) && !_capturing) {
StartCoroutine(Capture(new CaptureArgs {
frameCount = this.delayFrames,
camera = this.camera,
ctx = this
}));
}
}
struct CaptureArgs {
public int frameCount;
public Camera camera;
public DelayedCaptureBehaviour ctx;
}
IEnumerator Capture(CaptureArgs args) {
Camera camera = args.camera;
DelayedCaptureBehaviour ctx = args.ctx;
ctx._capturing = true;
bool enabled = camera?.enabled ?? false;
if (camera) { camera.enabled = true; }
// wait however many frames
int frame = 0;
while (frame < args.frameCount) {
frame++;
yield return null;
}
yield return new WaitForEndOfFrame();
// create our target texture, and copy the camera's pixels into it
Texture2D screenshotTex;
if (camera?.targetTexture == null) {
screenshotTex = ScreenCapture.CaptureScreenshotAsTexture();
} else {
// camera renders to a render texture
RenderTexture.active = camera.targetTexture;
screenshotTex = new Texture2D(camera.targetTexture.width, camera.targetTexture.height, TextureFormat.RGB24, false);
screenshotTex.ReadPixels(new Rect(0, 0, screenshotTex.width, screenshotTex.height), 0, 0);
}
// dump to desktop
byte[] data = screenshotTex.EncodeToPNG();
string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
const string fname = "screenshot.png";
string fpath = dir + "/" + fname;
if (File.Exists(fpath)) {
File.Delete(fpath);
}
File.WriteAllBytes(fpath, data);
if (camera && !enabled) { camera.enabled = false; }
ctx._capturing = false;
Debug.Log("saved screenshot!");
UnityEngine.Object.Destroy(screenshotTex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment