Search code examples
camerapixeltexture2ddisplayunity-game-engine

Unity: Texture2D ReadPixels for specific Display


Unity has had support for multiple display outputs for a while now (up to 8).

With the ReadPixels function, you can specify an area to read from, and an origin coordinate. But I cannot specify a display number to perform the read on.

I need to be able to read pixels from a specific display (1-8) with a specific area and origin point.

How can I do this, please?


Solution

  • You can achieve ReadPixels for a specific screen/display. You have to do the following:

    Before I start, I assume you have a number of cameras which are each rendering to a different display. The cameras must not have a RenderTexture attached to them in order to output to a display.

    Define a function which does the following:

    1. Assign the desired camera a temporary RenderTexture
    2. Use RenderTexture.active = *temporary render texture* to make the currently active rendertexture equal the temporary one you just created
    3. Use ReadPixels to read in pixels into a temporary texture2d using an appropriate Rect. This will read from the currently active RenderTexture
    4. Call Apply() on the texture2d
    5. Set the RenderTexture.active and camera RenderTexture to null

    The idea is that ReadPixels works on the currently Active RenderTexture.

    The code should look something like this:

        outputCam.targetTexture = outputCamRenderTexture;
        RenderTexture.active = outputCamRenderTexture;
        outputCam.Render ();
        tempResidualTex.ReadPixels (screenRect, 0, 0);
        tempResidualTex.Apply ();
    
        RenderTexture.active = null;
        outputCam.targetTexture = null;