My problem is simple, I need to make a video from a simulation that I run in Unity. I first wanted to use tools like FRAPS, but my framerate is now too slow. So I thought of simply saving my camera output every frame in a file, and then i will be able to create my movie from the pictures. To do so I fixed the framerate : “Time.captureFramerate = 50;” and each frame I save the output in the Update function of the script handling my cameras :
Camera cam = cameras[currentCamera];
int width = (int)cam.pixelWidth;
int height = (int)cam.pixelHeight;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
RenderTexture texture = new RenderTexture(width,height,24);
Rect save = cameras[currentCamera].rect;
cam.rect = new Rect(0.0f,0.0f,1.0f,1.0f);
cam.targetTexture = texture;
cam.Render();
cam.rect = save;
RenderTexture.active = texture;
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
byte[] bytes = tex.EncodeToPNG();
string filename = Application.dataPath + "/images/" + "Img-"+Time.fixedTime+ ".png";
System.IO.File.WriteAllBytes(filename, bytes);
cam.targetTexture = null;
RenderTexture.active = null;
Object.DestroyImmediate(texture);
Object.DestroyImmediate(tex);
cam.rect = save;
The problem is that it only saves a few frames per second instead of the 50 frames. It seems that the Update function is not called everytime. Does anyone knows what is hapenninng ? How could I fix this ?
I just tested to save my frames using " Application.CaptureScreenshot(Application.dataPath + “/images/” + “Img-”+Time.fixedTime+ “.png”);" instead of my code, but I still have the same issue, only some of the frames are being saved. Any suggestion ?
Application.CaptureScreenshot is probably quite a slow process, so the computer may only be running at only a few frames per second, hence the small number of captured frames.
A possible alternative is to set Time.timeScale to zero. Capture a screenshot, advance time by 1 frame using Time.time, then capture the next screenshot, and keep repeating. You might need to use ParticleSystem.Simulate or ParticleEmitter.Simulate to advance those systems.
Ok, thx for the tip but the time spend on CaptureScreeshot should not affect my frame rate since I was setting the Time.captureFramerate value. I finally solved my problem, and I feel a bit stupid now. I was setting the captureFrameRate value in the Awake function of my script instead of the Start function. It’s now working like a charm.
Why do you feel stupid? I just encountered the same problem, and IMHO that’s a stupid bug in Unity, nothing else: If you set Time.captureFramerate in Awake(), it is ignored, and reset to 0.
Also note that this bug was INTRODUCED in Unity 4.x, as I just confirmed - Unity 3.5 works as expected.