Runtime Texture Baking

For runtime texture baking, first, it is necessary to bake Shader Graph nodes into a .shader file. This is done by the Bake Shader button:

Only the nodes connected to the Shader Graph Baker are used in the generated .shader file.

After baking a .shader, it can be used in runtime scripts by creating a material using this shader. Properties of this material can be adjust in runtime too using Unity methods like SetFloat, SetVector, SetColor and etc.

Run-time API for baking material into a texture can be brought into scope with this using directive:

using AmazingAssets.ShaderGraphBaker;

Now Unity Material class will have new ShaderGraphBaker extension with BakeTexture2D(...) and UpdateRenderTexture(...) methods.

// Example of baking material to texture and saving it to a file

using System.IO;
using UnityEngine;

using AmazingAssets.ShaderGraphBaker;


public class ExampleScript : MonoBehaviour
{
    void SaveMaterialToTexture(Material material, string savePath)
    {
        //Baking material to texture
        Texture2D texture = material.ShaderGraphBaker().BakeTexture2D(1024, false, false);


        //Encoding texture to PNG
        byte[] bytes = texture.EncodeToPNG();


        //Save file
        File.WriteAllBytes(Path.Combine(savePath, material.name + "png"), bytes);


        //Cleanup
        DestroyImmediate(texture);
    }
}

BakeTexture2D

Texture2D BakeTexture2D(int resolution, bool hasMipmap, bool linear)

Creates Texture2D object and renders material into it.

resolution - Generated texture's resolution.

hasMipmap - should the created texture contain mipmaps?

linear - if baking Normal or Raw Data texture, then this value should be true. It is false for Color Map texture.

UpdateRenderTexture

void UpdateRenderTexture(ref RenderTexture renderTexture)

Renders material into the provided renderTexture. For rendering Normal and Raw Data texture, make sure the renderTexture is created using the linear flag.

Last updated