How to read RGB values of RenderTexture in Unity

  • Unity で RenderTexture の RGB の値を CPU で取得するコードの例です.
int width  = 128;
int height = 128;
RenderTexture src_render_texture = 
    new RenderTexture( width, height, 0,
                       RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear );
src_render_texture.autoGenerateMips  = false;
src_render_texture.enableRandomWrite = false;
src_render_texture.filterMode        = FilterMode.Bilinear;

Texture2D tmp_texture_2d = 
    new Texture2D( width, height, TextureFormat.RGBAFloat, false );
RenderTexture.active = src_render_texture;
Rect rect = new Rect( 0, 0, width, height );

tmp_texture_2d.ReadPixels( rect, 0, 0 );
for ( int pixel_y = 0; pixel_y < height; ++pixel_y )
{
    for ( int pixel_x = 0; pixel_x < width; ++pixel_x )
    {
          Color c = tmp_texture_2d.GetPixel( pixel_x, pixel_y );
          Debug.LogFormat( "pixel[{0},{1}] = {2}", pixel_x, pixel_y, c );
     }
}