Hi, I’m trying to achieve an offscreen rendering implementation for my project. The progress is ok I can actually render something without showing it on the screen nor wait for the renderer life circle. The problem is, after the render has finished, Unity took a long time break (freeze) before start rendering the next frame. Even the offscreen rendering process has taken for only 348ms, but Unity will be freezing for somewhere between 5-6 secs before the next frame start rendering in my case. I understand that is probably because I’m still done stuff in the rendering life circle and Unity probably has to be sync with the main thread or for some reason. But it’s there any way I can prevent the break? Or perhaps there’s a better practice for my case? Here’s code:
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class OffscreenRendering : MonoBehaviour
{
public int maxFrame = 120;
public bool render;
public Material material;
public Animator animator;
public SkinnedMeshRenderer[] skinnedMeshRenderers;
public void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (render)
{
float startTime = Time.realtimeSinceStartup;
Debug.Log("Start render at: " + startTime);
RenderTexture rt = new RenderTexture(source);
Mesh mesh = new Mesh();
for (int i = 0; i < maxFrame; i++)
{
rt.Create();
Graphics.SetRenderTarget(rt);
Graphics.Blit(source, rt);
animator.Update(1.0f / Application.targetFrameRate);
material.SetPass(0);
for (int j = 0; j < skinnedMeshRenderers.Length; j++)
{
skinnedMeshRenderers[j].BakeMesh(mesh);
Graphics.DrawMeshNow(mesh, Vector3.left, Quaternion.identity);
}
//MeshBlit.SaveFrame(rt, i + ".png"); Save the frame on disk.
Graphics.SetRenderTarget(null);
rt.Release();
}
Debug.LogFormat("Render finished at: {0}, span: {1}", Time.realtimeSinceStartup, Time.realtimeSinceStartup - startTime);
render = false;
}
Graphics.SetRenderTarget(source);
Graphics.Blit(source, destination);
}
}