Runtime Sprite Atlas Packing

I’m curious about how to add sprites to a Sprite Atlas during runtime and pack them. I am aware that the SpriteAtlasExtension APIs are only available in Editor code, so I cannot use them.

You’re correct that Unity’s built-in SpriteAtlas and related APIs are not available at runtime. However, you can create a custom solution for packing sprites into a texture atlas during runtime. One approach is to use the open-source library called “[MaxRectsBinPack][1]”.

Here is an example of using that library to pack sprites into a texture atlas at runtime:

using System.Collections.Generic;
using UnityEngine;
using Unity.Mathematics.Geometry;

public class RuntimeSpriteAtlasPacker : MonoBehaviour
{
    public Texture2D PackSprites(List<Sprite> sprites, int atlasSize, int padding)
    {
        MaxRectsBinPack binPack = new MaxRectsBinPack(atlasSize, atlasSize);
        List<Rect> rects = new List<Rect>();

        // Pack sprites in the bin pack
        foreach (Sprite sprite in sprites)
        {
            int width = Mathf.CeilToInt(sprite.rect.width) + padding;
            int height = Mathf.CeilToInt(sprite.rect.height) + padding;
            Rect packedRect = binPack.Insert(width, height, MaxRectsBinPack.FreeRectChoiceHeuristic.RectBestShortSideFit);
            rects.Add(packedRect);
        }

        // Create the atlas texture
        Texture2D atlas = new Texture2D(atlasSize, atlasSize);
        for (int i = 0; i < sprites.Count; i++)
        {
            Color[] pixels = sprites*.texture.GetPixels(*

(int)sprites*.rect.x,*
(int)sprites*.rect.y,*
(int)sprites*.rect.width,*
(int)sprites*.rect.height*
);
atlas.SetPixels((int)rects.x, (int)rects.y, (int)rects_.width - padding, (int)rects*.height - padding, pixels);
}*_

atlas.Apply();
return atlas;
}
}
Example usage:
public class ExampleUsage : MonoBehaviour
{
public List spritesToPack;
public int atlasSize = 1024;
public int padding = 2;

void Start()
{
RuntimeSpriteAtlasPacker packer = new RuntimeSpriteAtlasPacker();
Texture2D packedAtlas = packer.PackSprites(spritesToPack, atlasSize, padding);

// Use the packedAtlas texture as needed
}
}

_*[1]: https://github.com/jderrough/UnitySlippyMap/blob/master/Assets/UnitySlippyMap/Helpers/MaxRectsBinPack.cs*_