Search Unity

Question Bake a texture from shader

Discussion in 'Shader Graph' started by bartuq, Oct 15, 2021.

  1. bartuq

    bartuq

    Joined:
    Sep 26, 2016
    Posts:
    127
    I would like to export my grid created in Shader Graph as a texture, but the exported png file doesn't contain any graphics.
    gridshader2.png gridshader1.png

    Code (CSharp):
    1.     public int size = 900;
    2.     public Material material;
    3.     public void ExportAsPng()
    4.     {
    5.         // Create a temporary RenderTexture of the same size as the texture
    6.         RenderTexture tmp = RenderTexture.GetTemporary(
    7.                             size,
    8.                             size,
    9.                             0,
    10.                             RenderTextureFormat.Default,
    11.                             RenderTextureReadWrite.Linear);
    12.  
    13.         // Blit the pixels on texture to the RenderTexture
    14.         Graphics.Blit(null, tmp, material);
    15.  
    16.         // Backup the currently set RenderTexture
    17.         RenderTexture previous = RenderTexture.active;
    18.  
    19.         // Set the current RenderTexture to the temporary one we created
    20.         RenderTexture.active = tmp;
    21.  
    22.         // Create a new readable Texture2D to copy the pixels to it
    23.         Texture2D myTexture2D = new Texture2D(size, size);
    24.  
    25.         // Copy the pixels from the RenderTexture to the new Texture
    26.         myTexture2D.ReadPixels(new Rect(0, 0, tmp.width, tmp.height), 0, 0);
    27.         myTexture2D.Apply();
    28.  
    29.         // Reset the active RenderTexture
    30.         RenderTexture.active = previous;
    31.  
    32.         // Release the temporary RenderTexture
    33.         RenderTexture.ReleaseTemporary(tmp);
    34.  
    35. #if UNITY_EDITOR
    36.         string folder = $"{Directory.GetParent(Application.dataPath)}/Images";
    37. #else
    38.         string folder = $"{Application.dataPath}/Images";
    39. #endif
    40.         string path = Path.Combine(folder, "Test.png");
    41.         byte[] bytes = myTexture2D.EncodeToPNG();
    42.         File.WriteAllBytes(path, bytes);
    43.     }
     
  2. KHam256

    KHam256

    Joined:
    Sep 17, 2016
    Posts:
    19
    Did you ever figure this out?
     
  3. bartuq

    bartuq

    Joined:
    Sep 26, 2016
    Posts:
    127
    Hi, nope. If anything changes, I will write here.
     
    KHam256 likes this.
  4. Arkhivrag

    Arkhivrag

    Joined:
    Apr 25, 2012
    Posts:
    2,982
    Graphics.Blit method won't work with Shader Graph files.
    You can check how Shader Graph uses PreviewManager.cs for rendering preview nodes.

    If anyone needs ready to use solution, check Shader Graph Baker tool on the Asset Store:
    upload_2022-11-20_19-11-34.png