SpriteAtlas resizing via script

Hi!

I’m trying make a routine for automating the creation of SpriteAtlas variants. The imagined routine is:

  • Duplicate a master atlas.
  • Set duplicated atlas as variant of master.
  • Set scale on duplicated atlas.

Duplicating an asset is easy, but accessing anything of the SpriteAtlas is not. From what I can see of the documentation, SpriteAtlas is completely sealed off.

As an alternative approach, I looked into the Sprite Packer to see if I could pack a new atlas, but the packer is sealed off too.

I could probably do all of this via reflection, but I suspect that would break easily and cause more work in the future.

Has anyone tried anything similar and have any valuable lessons to share?

Thomas

I ended up using reflection. It’ll probably break easily, so I have to add code to throw warnings when it does.

This is the basics of how I solved it:

SpriteAtlas masterAtlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(masterPath);
SpriteAtlas variantAtlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(variantPath);

Assembly editorAssembly = Assembly.GetAssembly(typeof(Editor));
Type spriteAtlasExt = editorAssembly.GetType("UnityEditor.U2D.SpriteAtlasExtensions");
Type spriteAtlasUtil = editorAssembly.GetType("UnityEditor.U2D.SpriteAtlasUtility");

spriteAtlasExt
    .GetMethod("SetIsVariant")
    .Invoke(variantAtlas, new object[] { variantAtlas, true });

spriteAtlasExt
    .GetMethod("SetMasterAtlas")
    .Invoke(variantAtlas, new object[] { variantAtlas, masterAtlas });

spriteAtlasExt
    .GetMethod("SetVariantMultiplier")
    .Invoke(variantAtlas, new object[] { variantAtlas, scale });

spriteAtlasUtil
    .GetMethod("PackAtlases", BindingFlags.Static | BindingFlags.NonPublic)
    .Invoke(null, new object[] {
        new SpriteAtlas[] { variantAtlas },
        EditorUserBuildSettings.activeBuildTarget
    });

You can have a look at the source code for the UnityEngine.U2D namespace at UnityDecompiled/UnityEditor/UnityEditor.U2D at b4b209f8d1c93d66f560bf23c81bc0910cef177c · MattRix/UnityDecompiled · GitHub