Search Unity

Question Baking shader/material output into image. Texture2D.ReadPixels not working correctly.

Discussion in 'General Graphics' started by Heurazio, Sep 4, 2022.

  1. Heurazio

    Heurazio

    Joined:
    Dec 24, 2021
    Posts:
    8
    Hi,

    I try to bake a shader material into a PNG. For this, I use the following code

    Code (CSharp):
    1.  
    2. void BakeTexture()
    3. {
    4.     var renderTexture = RenderTexture.GetTemporary(this._resolution.x, this._resolution.y, 0, GraphicsFormat.R8G8B8A8_UNorm, 1);
    5.  
    6.     Graphics.Blit(null, renderTexture, this._material);
    7.  
    8.     var texture = new Texture2D(this._resolution.x, this._resolution.y);
    9.  
    10.     RenderTexture.active = renderTexture;
    11.     var start = new Vector2(-this._resolution.x / 2f, -this._resolution.y / 2f);
    12.     var rect = new Rect(start, this._resolution);
    13.     Debug.Log($"Draw rect: {rect}");
    14.     texture.ReadPixels(rect, 0, 0);
    15.     texture.Apply();
    16.  
    17.     var png = texture.EncodeToPNG();
    18.     File.WriteAllBytes($"{this._folderPath}/{this._files}.png", png);
    19.     AssetDatabase.Refresh();
    20.  
    21.     RenderTexture.active = null;
    22.     RenderTexture.ReleaseTemporary(renderTexture);
    23.     DestroyImmediate(texture);
    24. }
    25.  
    26.  
    The shader applied to a sprite looks like this (example):
    View attachment 1112415

    As you can see, in this case, it's a 60x30 units sized sprite which is centered at 0x0 (Lower-Left should be at -30x-15).

    When I run the code above I get the following output:
    View attachment 1112418

    I already figured out, that when I use Vector2.zero as start (instead of the x/y-offset), it renders the full image like this
    View attachment 1112421

    but as you can see it is only the area in the world from 0x0 to 1x1 and not the whole area from -30x-15 to 30x15.

    What am I doing wrong?