I know that the Unity API does not play nice with threading, as evidenced by the errors that were returned when I tried and the comments throughout this site. However, while looking around I saw in this question that someone claimed to be able to thread Application.CaptureScreenshot, among other capture methods. For the others, I understand that he was threading the actual encoding after the Unity method was called. However, I fail to see how he could make Application.CaptureScreenshot work. When I currently use Application.CaptureScreenshot without slowing down game time (with Time.captureFramerate), it runs at about 6 fps regardless of CPU power (tested on multiple) due to the amount of work it’s doing writing to disk. In the link, he claims to have been able to make it run at 30+ fps using threading. Am I missing how this is possible, or is his claim a lot more complicated than he’s making it sound?
I have had success threading a texture2d capture, I haven’t tried threading CaptureScreenshot but I have had success getting pixel data out of a Texture2D. Note: the following solution still affects your framerate, but if you can optimise it by
- reducing the area of of the area of the screen you capture
- scaling down the captured texture2d to reduce bytes written to disk
You could try doing something similar with Application.CaptureScreenshot() but I’m not sure how that will behave with threads.
Thread workerThread;
SaveFile worker;
void Start()
{
Texture2D texture = new Texture(Screen.width, Screen.height);
texture.ReadPixels(new Rect(0f, 0f, Screen.width, Screen.height);
byte[] dataToSave = texture.EncodeToPNG();
worker = new Worker(dataToSave);
workerThread = new Thread(new Thread.ThreadStart(worker.SaveData));
}
class SaveFile
{
byte[] data;
public SaveFile(byte[] data)
{
this.data = new byte[data.Length];
data.CopyTo(this.data, 0);
}
public void SaveData()
{
System.IO.File.WriteAllBytes("screenshot.png", data);
}
}