Unity3D and Merge Textures Tutorial

So a while I go I ran into an issue where I’d want to merge two images together but I needed to do it on run time. Sometimes you need to generate images by combining a few or more images together as saving them as separate files is not very dynamic. This could potentially be used to merge character sprites with armor sprites in a 2D game or different cards and rarities, the possibilities are endless! 😀

The easiest to merge are textures that are of the same size. You would just take the bottom image and slap the top one on it like a sticker without having to worry about any pixel offsets, like this:

Texture2D MergeTextures(Texture2D texture_1, Texture2D texture_2) {

    Texture2D merge_result = new Texture2D(texture_1.width, texture_1.height);

    for (int i = 0; i < merge_result.width; i++) {
        for (int j = 0; j < merge_result.height; j++) {

            Color tex1_color = texture_1.GetPixel(i, j);
            Color tex2_color = texture_2.GetPixel(i, j);
            Color merged_color = Color.Lerp(tex1_color, tex2_color, tex2_color.a / 1);

            merge_result.SetPixel(i, j, merged_color);


    return merge_result;


Make sure the textures you are using are set to read/write enabled and The compression format is set to a supported one or you will be seeing some errors.

Unity3D and Merge Textures

How to use
// tex_bottom and tex_top are set as public types of Texture2D
// which I set to my textures in the inspector
Texture2D tex_result = MergeTextures(tex_bottom, tex_top);
Saving the merge result to file
File.WriteAllBytes(Application.dataPath + "/test.png", tex_result.EncodeToPNG());
Using the Merged result as a sprite on a sprite renderer
// output_sprite is a public SpriteRenderer that I set in the inspector

Rect sprite_rect = new Rect(0, 0, tex_result.width, tex_result.height);
output_sprite.sprite = Sprite.Create(tex_result, sprite_rect, new Vector2(0.5f, 0.5f));

Unity3D and Merge Textures

Leave a Reply

Your email address will not be published. Required fields are marked *