在无头模式下单独运行Unity,同时截取屏幕截图

我需要创建一个以无头模式(使用-batchmode命令)运行的统一项目,但是它必须每隔一秒捕获截图并将其写入文件。

我明白,在无头模式下,你需要强制调用Camera.Render()来渲染任何东西。

看起来第一个截图被捕获后,时间会冻结。 第一个屏幕截图看起来绝对正确,但后面的所有屏幕截图与第一个屏幕截图相同,意味着时间已经冻结。

我需要做些什么来确保场景随着时间的推移正确更新,并且相机能够每秒渲染一次?

using System; using System.Collections; using System.IO; using UnityEngine; namespace Assets { public class Particles : MonoBehaviour { private const float screenshotEvery = 1.0f; private float timerCount = 0f; private float elapsedSecond; private const float maxElapsedSecond = 20; private string screenshotsDirectory = "UnityHeadlessRenderingScreenshots"; public Camera camOV; public RenderTexture currentRT; // Use this for initialization public void Start () { Application.targetFrameRate = 60; if (Directory.Exists(screenshotsDirectory)) { Directory.Delete(screenshotsDirectory, true); } if (!Application.isEditor) { Directory.CreateDirectory(screenshotsDirectory); camOV.targetTexture = currentRT; } } // Update is called once per frame public void Update () { elapsedSecond += Time.deltaTime; timerCount += Time.deltaTime; if (Application.isEditor) { return; } if (elapsedSecond <= maxElapsedSecond) { if (timerCount >= screenshotEvery) { TakeScreenShot(); timerCount = 0f; } } else { Application.Quit(); } } public void TakeScreenShot() { RenderTexture.active = camOV.targetTexture; camOV.Render(); Texture2D imageOverview = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false); imageOverview.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0); imageOverview.Apply(); RenderTexture.active = currentRT; // Encode texture into PNG byte[] bytes = imageOverview.EncodeToPNG(); // save in memory string filename = elapsedSecond + ".png"; var path = screenshotsDirectory + "/" + filename; File.WriteAllBytes(path, bytes); } } } 

提前谢谢了!