Unity如何将相机图像保存速率从约60帧/秒降至10帧/秒?
Fixing Frame Saving Rate to 10 FPS in Unity
Hey Eduardas, let's get that frame saving rate under control! The core issue here is that your current code runs in Update(), which executes once per frame—usually around 60 times per second on most setups. To drop down to exactly 10 frames per second, we need to add a time-based check to only save frames at 0.1-second intervals.
Here's the adjusted code with explanations:
// Track time elapsed since our last frame save private float timeSinceLastSave = 0f; // 10 FPS = 1 save every 0.1 seconds private const float saveInterval = 0.1f; void Update() { if (TLB) { // Add the time since the last frame to our tracker timeSinceLastSave += Time.deltaTime; // Only run the save logic when our interval is reached if (timeSinceLastSave >= saveInterval) { DirectoryInfo p = new DirectoryInfo(path); FileInfo[] files = p.GetFiles(); saveFrame(path, "TLB", fileCounter); fileCounter = files.Length + 1; // Reset the timer so we count down to the next save timeSinceLastSave = 0f; } } } void saveFrame(string path, string type, int counter) { RenderTexture rt = new RenderTexture(frameWidth, frameHeight, 24); Camera targetCamera = GetComponentInChildren<Camera>(); targetCamera.targetTexture = rt; // Force the camera to render to our texture targetCamera.Render(); // Convert the RenderTexture to a saveable Texture2D Texture2D texture = new Texture2D(frameWidth, frameHeight); RenderTexture.active = rt; texture.ReadPixels(new Rect(0, 0, frameWidth, frameHeight), 0, 0); texture.Apply(); // Save the texture as a PNG (swap with EncodeToJPG() if needed) byte[] imageBytes = texture.EncodeToPNG(); string fullFilePath = Path.Combine(path, $"{type}_{counter}.png"); File.WriteAllBytes(fullFilePath, imageBytes); // Critical: Clean up resources to avoid memory leaks RenderTexture.active = null; Destroy(rt); Destroy(texture); targetCamera.targetTexture = null; }
Key Notes:
- Time-based control: Using
Time.deltaTimeensures we account for variable frame rates—even if your game dips below 60 FPS, we'll still save exactly 10 frames per second. - Resource cleanup: I added proper disposal of
RenderTextureandTexture2Din thesaveFramemethod. Skipping this would lead to memory leaks over time, which is a common pitfall with texture operations in Unity. - Flexibility: If you ever want to adjust the save rate, just change the
saveIntervalvalue (e.g., 0.5 for 2 FPS, 0.05 for 20 FPS).
If you notice any jitter or want even more precise timing, you could move the save logic to FixedUpdate() instead (since it runs at a fixed time step), but the Update() approach with deltaTime should work perfectly for most cases.
内容的提问来源于stack exchange,提问作者Eduardas
相关产品推荐
相关产品推荐

