- Home /
ReadPixels Performance
I have a 3d scene with a special "mouse picker" camera that uses a solid color replacement shader and renders to a RenderTexture. Each object has a unique color that allows me to identify what object the mouse is currently under. The camera uses a custom projection matrix that allows us to use an extremely small (2x2) render texture which is only the few pixels under the mouse pointer.
All this works great. What doesn't work great is the performance of the call to Texture2D.GetPixels. On modern hardware the game doesn't even skip a beat. However, on older hardware, that one function call is extremely expensive. It also seems to be extremely dependent on the size of the screen buffer. The higher the resolution, the worse the performance hit from this call.
Here are some specifics:
The camera is using forward rendering
The render texture is created using:
new RenderTexture( (int)( 2 * AspectRatio ), 2, 16, RenderTextureFormat.Default, RenderTextureReadWrite.Default);
useMipMap is set to false
ReadPixels is called in the OnPostRender for the picker camera:
readTexture.ReadPixels(new Rect(pickPosition.x, pickPosition.y, 1, 1), 0, 0, false); readTexture.Apply();
I tried delaying the ReadPixels call for a few frames and it makes no difference
Is there something I am doing wrong? Is there a way to defer the ReadPixels call so it doesn't freeze up the main thread? Is there a completely different way to do this? Any help would be appreciated!
Total shot in the dark, but is ReadPixels32() any faster?
I don't see any reference for ReadPixels32. Are you referring to GetPixels32?
EDIT: Just for fun I tried calling GetPixels32()[0] ins$$anonymous$$d of GetPixel(0,0) but it didn't make a difference.
How come you can't just use a simple raycast from mouse point to check object name?, ins$$anonymous$$d of doing pixel color lookup...
Yes it is extremely slow. No, all Unity code is single-threaded. Your only bet is to use a different method of getting the pixel value.
Just out of curiosity, have you tried rendering everything to a render texture, and using GetPixel on that, and thereby reducing the chance you rerender the entire scene (albiet just a 2x2 image of it)? I assume that method led you to this, but thought I'd provide an alternative.
Are you doing this every update? Is there any possibility of avoiding the problem altogether by reducing the amount of GetPixel calls needed?
Sorry I can't help you directly. I hate how slow this is...
Hey there, did you ever find a solution to this/ alternative to using GetPixels?
Your answer
Follow this Question
Related Questions
Check if mouse is over GUI element using Rendertexture? 1 Answer
Why is ReadPixels on my RenderTexture creating a pure gray texture? 1 Answer
Camera size and RenderTexture 1 Answer
Unity4 problem - Bypassing camera renderTexture with ReadPixels but system out of memory 1 Answer
Can a Texture2D be created at runtime from a snapshot of a RenderTexture? 3 Answers