Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Bug Reading the data asynchronously from ComputeBuffer causes Gfx.WaitForPresentOnGfxThread lag

Discussion in 'General Graphics' started by KUNGERMOoN, Jul 11, 2023.



    Apr 29, 2020
    I'm using unity 2022
    I'm trying to write a script that could read data from a compute buffer. I tried using ComputeBuffer.GetData() but it caused CPU to freeze until all GPU calculation were done. I tried using AsyncGPUReadback (as shown in the script below).
    Code (CSharp):
    1. using Unity.Collections;
    2. using UnityEngine;
    3. using UnityEngine.Rendering;
    5. public class Test : MonoBehaviour
    6. {
    7.     public ComputeShader Shader;
    8.     ComputeBuffer buffer;
    10.     AsyncGPUReadbackRequest request;
    12.     NativeArray<int> Data;
    14.     private void Awake()
    15.     {
    16.         Data = new NativeArray<int>(10000000, Allocator.Persistent);
    17.         buffer = new ComputeBuffer(Data.Length, sizeof(int));
    18.         buffer.SetData(Data);
    20.         Shader.SetBuffer(0, "buffer", buffer);
    22.         request = AsyncGPUReadback.Request(buffer);
    23.     }
    25.     private void Update()
    26.     {
    27.         if (request.done && !request.hasError)
    28.         {
    29.             Data.Dispose();
    30.             Data = request.GetData<int>();
    31.             request = AsyncGPUReadback.Request(buffer);
    32.         }
    33.     }
    35.     private void OnDestroy()
    36.     {
    37.         buffer.Dispose();
    38.         Data.Dispose();
    39.     }
    40. }
    However, the following code causes the Gfx.WaitForPresentOnGfxThread lag spikes to appear in build:
    Unity documentation recommends to check the profiler timeline to see what Render Thread is spending time on when facing problems with Gfx.WaitForPresentOnGfxThread. The profiler shows that Render Thread is busy with Gfx.UpdateAsyncReadbackData. My guess is that it's not caused by GPU computations taking too long (the Compute Shader in the script is never being dispatched, the scene has no skybox, camera or any other GameObjects - except the one with the script), but rather by the AsyncReadbackRequest internal behaviour (as the name suggests). If I'm right,
    1. Is it a bug or an intended behaviour (it's strange that updating AsyncGPUReadback, which's sole purpose of existence it to get data from GPU without freezing CPU, in fact freezes the CPU)
    2. Is there any workaround for this / any way to minimalize this problem?

    Here's a minimal reproduction project including the above script: