Graphics.Blit in a loop

Hi Everyone,

I’m having a little issue where I’m using RenderTextures as framebuffers. What I want to do is blit to a RenderTexture in a loop, where I use the result of the last blit as the source for the next one.

For some reason it doesn’t work and I don’t know whether this is due to the loop running faster than the rendering does, or if there’s another reason for it. Basically here’s what I have:

for (int i = 0; i < 5; i++)
        {
            material.SetFloat("_i", i);

            if (i == 0)
            {
                Graphics.Blit(initInput, resultTex, material);
            }
            else
            {
                RenderTexture.active = resultTex;
                tempTex.ReadPixels(new Rect(0, 0, resultTex.width, resultTex.height), 0, 0);
                tempTex.Apply();

                Graphics.Blit(tempTex, resultTex, material);
            }
        }

Can anyone point me in the right direction here?

I’m not sure why it doesn’t work, but you want to avoid tempTex.ReadPixels, because this moves the pixels back from the GPU to the main memory. (Very slow compared to GPU only operations.)

What you want to have is two RenderTexture that you can alternate. So

  • initInput → resultTex1
  • resultTex1 → resultTex2
  • resultTex2 → resultTex1
  • resultTex1 → resultTex2
  • resultTex2 → resultTex1

The loop won’t be running faster than the rendering does, since all calls in there are blocking.