Unity以特定速率保存相机图像

在我的项目中,我将相机图像保存到一个文件夹中,但是每秒可节省约60。如何将保存的图像数量减少到每秒10张左右?


void Update()

    if (TLB)

    {

        DirectoryInfo p = new DirectoryInfo(path);

        FileInfo[] files = p.GetFiles();

        saveFrame(path, "TLB", fileCounter);

        fileCounter = files.Length + 1;

    }

}    


void saveFrame(string path, string type, int counter)

{

    RenderTexture rt = new RenderTexture(frameWidth, frameHeight, 24);

    GetComponentInChildren<Camera>().targetTexture = rt;

    Texture2D frame = new Texture2D(frameWidth, frameHeight, TextureFormat.RGB24, false);

    GetComponentInChildren<Camera>().Render();

    RenderTexture.active = rt;

    frame.ReadPixels(new Rect(0, 0, frameWidth, frameHeight), 0, 0);

    GetComponentInChildren<Camera>().targetTexture = null;

    RenderTexture.active = null;

    Destroy(rt);

    byte[] bytes = frame.EncodeToPNG();

    string filename = path + type + "/" + "/" + frameName(type, counter);

    File.WriteAllBytes(filename, bytes);

}


森林海
浏览 242回答 1
1回答

慕斯709654

在Unity中一定时间间隔后重复执行代码使用Update()方法:// Invoke the method after interval secondspublic float interval = 0.1f;// time counterfloat elapsed = 0f;void Update()&nbsp;{&nbsp; &nbsp; elapsed += Time.deltaTime;&nbsp; &nbsp; // if time is elapsed, reset the time counter and call the method.&nbsp; &nbsp; if (elapsed >= interval)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; elapsed = 0;&nbsp; &nbsp; &nbsp; &nbsp; TakeShot();&nbsp; &nbsp; }}void TakeShot()&nbsp;{&nbsp; &nbsp;// do your thing here...}使用InvokeRepeating()方法:// Invoke the method after interval secondspublic float interval = 0.1f;float delaySeconds = 0f; // delay the first call by secondsvoid Start(){&nbsp; &nbsp; InvokeRepeating("TakeShot", delaySeconds, interval);}void TakeShot()&nbsp;{&nbsp; &nbsp;// do your thing here...}注意:这两种方法都是framerate和time-scale依赖的。
打开App,查看更多内容
随时随地看视频慕课网APP