optimization
[URP] Fix Frame Spikes During Large RenderTexture PNG Saves
Solution
Unity 2018.2 - Unity 6.3.x
Published Mon, May 4
Saving high-resolution RenderTexture data via ReadPixels and EncodeToPNG causes significant frame spikes because these operations must occur on the main thread, blocking the rendering loop. Standard asynchronous tasks cannot be used for ReadPixels as it requires the GPU context available only on the primary thread.
Quick-Fix
Main-thread stalls occur during AsyncGPUReadback-less texture extraction. Use AsyncGPUReadback and threaded encoding to maintain smooth performance.
using UnityEngine;
using UnityEngine.Rendering;
using System.IO;
using Unity.Collections;
public class TexturePersistenceManager : MonoBehaviour
{
public void SaveRenderTextureAsync(RenderTexture sourceTexture, string destinationPath)
{
AsyncGPUReadback.Request(sourceTexture, 0, (AsyncGPUReadbackRequest request) => {
if (request.hasError)
{
Debug.LogError("GPU Readback failed.");
return;
}
NativeArray<byte> data = request.GetData<byte>();
byte[] encodedBytes = ImageConversion.EncodeNativeArrayToPNG(
data,
sourceTexture.graphicsFormat,
(uint)sourceTexture.width,
(uint)sourceTexture.height
);
File.WriteAllBytesAsync(destinationPath, encodedBytes);
});
}
}
Related Posts Haven't quite found a solution to your problem? We think these posts might help you.
[Utility] Save RenderTexture and Texture2D to Image Files[URP] Optimize Rendering Performance with Shader Variant PrewarmingDetermining Sprite Source Atlas vs Asset
Content inspired by a Unity discussion post.