Skip to content

Instantly share code, notes, and snippets.

@simonbroggi
Created October 31, 2017 09:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonbroggi/37966fbeb57721fa4a358fbaced11dde to your computer and use it in GitHub Desktop.
Save simonbroggi/37966fbeb57721fa4a358fbaced11dde to your computer and use it in GitHub Desktop.
Unity3D script to save all frames rendered by an attached camera to png files
using System;
using System.IO;
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class CaptureFrames : MonoBehaviour {
public int frameRate = 30;
string path;
Texture2D renderedImage;
void Start () {
// Save the frames in a folder named Capture/yyyy_MM_dd-HH_mm_ss/ next to the Assets
path = Application.dataPath;
if (Application.isEditor) {
path += "/../";
}
else if (Application.platform == RuntimePlatform.OSXPlayer) {
path += "/../../";
}
else if (Application.platform == RuntimePlatform.WindowsPlayer) {
path += "/../";
}
path += "Capture/";
if (!Directory.Exists(path)){
Directory.CreateDirectory(path);
}
path += DateTime.Now.ToString("yyyy_MM_dd-HH_mm_ss/");
if (!Directory.Exists(path)){
Directory.CreateDirectory(path);
}
}
void OnEnable () {
// Set the playback framerate (real time will not relate to game time after this).
Time.captureFramerate = frameRate;
}
void OnPostRender () {
if(renderedImage == null){
// Create an image with the same resolution as the cameras target render texture
Camera cam = GetComponent<Camera>();
if(cam.targetTexture != null){
renderedImage = new Texture2D(cam.targetTexture.width, cam.targetTexture.height);
}
else {
renderedImage = new Texture2D(Screen.width, Screen.height);
}
}
//read pixels from the active render texture
renderedImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
renderedImage.Apply();
//Save image to file
System.IO.File.WriteAllBytes(path+Time.frameCount.ToString("000000")+".png", renderedImage.EncodeToPNG());
}
void OnDisable(){
Destroy(renderedImage);
renderedImage = null;
Time.captureFramerate = 0;
}
}
@simonbroggi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment