- Home /
How to take screenshot of Unity camera every single frame?
Hi I'm working on a project in Unity where I want to take a screenshot of a Unity camera every single frame. That means if my FPS is 30, I should get 30 pictures per second. So far I can't seem to achieve that. Currently I'm getting about 20 - 30 FPS in my project but I only get about 1 - 2 pictures per second. But if I enter debug mode and manually go from one frame to the next it seems to work pretty well. How can I get it to work in real time? Here is the code I am using:
Camera snapCam;
public int horRes;
public int verRes;
void Awake()
{
snapCam = GetComponent<Camera>();
}
void Update()
{
Texture2D snapshot = new Texture2D(horRes, verRes, TextureFormat.RGB24, false);
snapCam.Render();
RenderTexture.active = snapCam.targetTexture;
snapshot.ReadPixels(new Rect(0, 0, horRes, verRes), 0, 0);
byte[] bytes = snapshot.EncodeToPNG();
string fileName = SnapshotName();
System.IO.File.WriteAllBytes(fileName, bytes);
Debug.Log("Snapshot Taken!");
}
}
string SnapshotName()
{
return string.Format("{0}/Snapshots/snap_{1}x{2}_{3}.png",
Application.dataPath,
horRes,
verRes,
System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
}
}
Answer by Devster2020 · Jun 29, 2021 at 09:20 AM
Hello @AnaPetrinec .
Your code is clear: every screenshot in the same second will be overwritten because the filename is the same! You need to set different name foreach frame using, for example, milliseconds in the DateTime format:
string SnapshotName()
{
return string.Format("{0}/Snapshots/snap_{1}x{2}_{3}.png",
Application.dataPath,
horRes,
verRes,
System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss.fff"));
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Editor Gizmo logic question? How do the gizmos move relative to camera 1 Answer
Dissable lights per camera? 2 Answers