Merging multiple textures / sprites into one texture.

This isn’t a question, it’s the answer. I spent a fair bit of time searching for one and had to cobble several things together to get what I wanted. I leave this for future generations.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpriteMerge : MonoBehaviour {
  
    public SpriteRenderer spriteRenderer;// assumes you've dragged a reference into this
    public Transform mergeInput;// a transform with a bunch of SpriteRenderers you want to merge

    // Use this for initialization
    void Start () {
        spriteRenderer.sprite = Create(new Vector2Int(2048, 2048), mergeInput);
    }

    /* Takes a transform holding many sprites as input and creates one flattened sprite out of them */
    public Sprite Create(Vector2Int size, Transform input) {
        var spriteRenderers = input.GetComponentsInChildren<SpriteRenderer>();
        if(spriteRenderers.Length == 0) {
            Debug.Log("No SpriteRenderers found in " + input.name + " for SpriteMerge");
            return null;
        }

        var targetTexture = new Texture2D(size.x, size.y, TextureFormat.RGBA32, false, false);
        targetTexture.filterMode = FilterMode.Point;
        var targetPixels = targetTexture.GetPixels();
        for(int i = 0; i < targetPixels.Length; i++) targetPixels[i] = Color.clear;// default pixels are not set
        var targetWidth = targetTexture.width;

        for(int i = 0; i < spriteRenderers.Length; i++) {
            var sr = spriteRenderers[i];
            var position = (Vector2)sr.transform.localPosition - sr.sprite.pivot;
            var p = new Vector2Int((int)position.x, (int)position.y);
            var sourceWidth = sr.sprite.texture.width;
            // if read/write is not enabled on texture (under Advanced) then this next line throws an error
            // no way to check this without Try/Catch :(
            var sourcePixels = sr.sprite.texture.GetPixels();
            for(int j = 0; j < sourcePixels.Length; j++) {
                var source = sourcePixels[j];
                var x = (j % sourceWidth) + p.x;
                var y = (j / sourceWidth) + p.y;
                var index = x + y * targetWidth;
                if(index > 0 && index < targetPixels.Length) {
                    var target = targetPixels[index];
                    if(target.a > 0) {
                        // alpha blend when we've already written to the target
                        float sourceAlpha = source.a;
                        float invSourceAlpha = 1f - source.a;
                        float alpha = sourceAlpha + invSourceAlpha * target.a;
                        Color result = (source * sourceAlpha + target * target.a * invSourceAlpha) / alpha;
                        result.a = alpha;
                        source = result;
                    }
                    targetPixels[index] = source;
                }
            }
        }

        targetTexture.SetPixels(targetPixels);
        targetTexture.Apply(false, true);// read/write is disabled in 2nd param to free up memory
        return Sprite.Create(targetTexture, new Rect(new Vector2(), size), new Vector2(), 1, 0, SpriteMeshType.FullRect);
    }
}

The use-case for this is for a lot of layered sprites that need to be flattened (like seriously so many, ouch). This is for a port of a game that heavily abused Flash’s ability to merge textures on the fly.

I looked at some functions within Unity.Graphics, but they seem shader-dependant which may cause me problems when compiling for older platforms and consoles. Perhaps someone could educate me on a more efficient method - finding out how to get this far was already a tough task since there is 5 years worth of misinformation and tediously long tutorial videos that aren’t quite what I needed.

3 Likes

Of course there had to be one crucial flaw in this plan: Rotated sprites.

Simply copying pixels isn’t enough. Fortunately I’m just rotating on 90 steps and also using flipX, so a bunch of x / y swaps and inversions fixes that. But you also have to account for how this affects the pivot of the sprite. It often leaves the sprite 1 pixel out of place. Why? Because by jumping around using the pivot we’re jumping into the next tile’s worth of pixels, when what we really want to do is some kind of inversion when we write the pixels.

How did I solve this? With a list of edge cases. I properly written matrix transformation with some kind of antialiasing would help for all rotations - but I didn’t need that so if you’re here looking for that I can’t help you. But I do have pixel perfect 90 rotations with sprite flipping on the X axis.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpriteMerge : MonoBehaviour {

    public SpriteRenderer spriteRenderer;// assumes you've dragged a reference into this
    public Transform mergeInput;// a transform with a bunch of SpriteRenderers you want to merge

    public enum ROT90 {
        NONE, ONE, TWO, THREE, NONE_FLIP, ONE_FLIP, TWO_FLIP, THREE_FLIP
    }

    void Start() {
        spriteRenderer.sprite = Create(new Vector2Int(2048, 2048), mergeInput);
    }

    public static Sprite Create(Vector2Int size, Transform input) {
        return Create(size, input, new Vector2Int());
    }

    /* Takes a transform holding many sprites as input and creates one flattened sprite out of them */
    public static Sprite Create(Vector2Int size, Transform input, Vector2Int offset) {
        var spriteRenderers = input.GetComponentsInChildren<SpriteRenderer>();
        if(spriteRenderers.Length == 0) {
            Debug.Log("No SpriteRenderers found in " + input.name + " for SpriteMerge");
            return null;
        }

        var targetTexture = new Texture2D(size.x, size.y, TextureFormat.RGBA32, false, false);
        targetTexture.filterMode = FilterMode.Point;
        var targetPixels = targetTexture.GetPixels();
        for(int i = 0; i < targetPixels.Length; i++) targetPixels[i] = Color.clear;// default pixels are not set
        var targetWidth = targetTexture.width;
        int tempX, tempY;

        for(int i = 0; i < spriteRenderers.Length; i++) {
            var sr = spriteRenderers[i];
            // Check for rotation:
            // not only does rotation do funny things with x/y, but by doing so you're jumping into the next tile
            // this means that the drawing ends up 1 pixel off, because you're not at the bottom of the current tile
            // but at the top of the next tile. Only 90 degree turns and sprite.flipX implemented so far.
            var rot = ROT90.NONE;
            var r = sr.transform.localRotation.eulerAngles.z;
            var pivot = sr.sprite.pivot;
            if(r == 90) {
                if(sr.flipX) {
                    rot = ROT90.ONE_FLIP;
                    pivot = new Vector2(-pivot.y + 1, -pivot.x + 1);
                } else {
                    rot = ROT90.ONE;
                    pivot = new Vector2(-pivot.y + 1, pivot.x);
                }
            } else if(r == 180) {
                if(sr.flipX) {
                    rot = ROT90.TWO_FLIP;
                    pivot = new Vector2(pivot.x, -pivot.y + 1);
                } else {
                    rot = ROT90.TWO;
                    pivot = new Vector2(pivot.x + 1, -pivot.y + 1);
                }
            } else if(r == 270) {// fun fact: if you enter -90 into the inspector it gets picked up as 270 in here
                if(sr.flipX) {
                    rot = ROT90.THREE_FLIP;
                    pivot = new Vector2(pivot.y, pivot.x);
                } else {
                    rot = ROT90.THREE;
                    pivot = new Vector2(pivot.y, -pivot.x + 1);
                }
            } else if(sr.flipX) {
                rot = ROT90.NONE_FLIP;
                pivot.x++;
            }
            var position = (Vector2)sr.transform.localPosition - pivot;
            Debug.Log(position);
            var p = new Vector2Int((int)position.x, (int)position.y) + offset;
            var sourceWidth = sr.sprite.texture.width;
            // if read/write is not enabled on texture (under Advanced) then this next bit throws an error
            // no way to check this without Try/Catch :(
            Color[] sourcePixels = null;
            try {
                sourcePixels = sr.sprite.texture.GetPixels();
            } catch(UnityException e) {
                if(e.Message.StartsWith("Texture '" + sr.sprite.texture.name + "' is not readable")) {
                    Debug.LogError("Please enable read/write on texture [" + sr.sprite.texture.name + "]");
                }
            }
            for(int j = 0; j < sourcePixels.Length; j++) {
                var source = sourcePixels[j];
                var x = j % sourceWidth;
                var y = j / sourceWidth;

                if(rot != 0) {
                    tempX = x;
                    tempY = y;
                    switch(rot) {
                        case ROT90.NONE_FLIP:
                            x = -tempX;
                            y = tempY;
                            break;
                        case ROT90.ONE:
                            x = -tempY;
                            y = tempX;
                            break;
                        case ROT90.ONE_FLIP:
                            x = -tempY;
                            y = -tempX;
                            break;
                        case ROT90.TWO:
                            x = -tempX;
                            y = -tempY;
                            break;
                        case ROT90.TWO_FLIP:
                            x = tempX;
                            y = -tempY;
                            break;
                        case ROT90.THREE:
                            x = tempY;
                            y = -tempX;
                            break;
                        case ROT90.THREE_FLIP:
                            x = tempY;
                            y = tempX;
                            break;
                    }
                }

                var index = (x + p.x) + (y + p.y) * targetWidth;
                if(index > 0 && index < targetPixels.Length) {
                    var target = targetPixels[index];
                    if(target.a > 0) {
                        // alpha blend when we've already written to the target
                        float sourceAlpha = source.a;
                        float invSourceAlpha = 1f - source.a;
                        float alpha = sourceAlpha + invSourceAlpha * target.a;
                        Color result = (source * sourceAlpha + target * target.a * invSourceAlpha) / alpha;
                        result.a = alpha;
                        source = result;
                    }
                    targetPixels[index] = source;
                }
            }
        }

        targetTexture.SetPixels(targetPixels);
        targetTexture.Apply(false, true);// read/write is disabled in 2nd param to free up memory
        return Sprite.Create(targetTexture, new Rect(new Vector2(), size), new Vector2(), 1, 1, SpriteMeshType.FullRect, new Vector4(2, 2, 2, 2));
    }
}

If you have a cleaner / more sensible approach then do comment.

2 Likes

Thanks buddy

FWIW I ran into the same problem, but I ended up solving it by putting my sprites into a world space canvas with sorting groups within the canvas. I was on the verge of either heavily modifying your code to allow for rendering text, or using raw OpenGL calls to blit things together before I hit upon this issue (My problem I was trying to solve was massive amounts of Z-fighting among the different parts of a playing card and between separate cards)

Great script man , how do we make it so the merge tool takes the transforms.positions into account, say I want the final sprite combine to have sprite A away 5cm from sprite B

You literally put the final sprite 5cm from sprite B. It’s effectively taking a screenshot but doing it sprite by sprite away from a camera.

If I were to try to do this today I would probably just set up a separate camera and have it render to a texture. That way I would be able to use shaders, set the camera to only render what I want, etc. It’s also much faster.

Thank you I am trying to put the sprite renderers children with distance between them but its not reflected when merging the layers.

But Im going to try the render camera as you said its great to be able to use shaders. So I am trying this approach now
https://answers.unity.com/questions/733240/how-to-take-a-screenshot-and-apply-it-as-a-texture.html
but the png resultant has no transparency… I wonder how I can make it

gone back to your method , I think the problem is when you are not using pixel per unit=1 then the distance of the objects is not working, I wonder how I can change the formula

Ok the solution was to do this:

            Vector2 position = (Vector2)sr.transform.localPosition * ppu - sr.sprite.pivot;
            Vector2Int pRounded = new Vector2Int((int)position.x, (int)position.y);