How to add sprites via code to pack list for Sprite Atlas V2

I am using Sprite Atlas V2. I have created a sprite atlas, and in the inspector there is a list to add sprites to be packed in this atlas. I have thousands of sprites from various asset packs. I have a script that finds them in my scenes. How do I add them to my sprite atlas?

I have tried the following:

atlas.Add(objectsToAdd.ToArray());
-OR-
SpriteAtlasExtensions.Add(atlas, objectsToAdd.ToArray());

Both of those lines “work”, aka: no errors. But the sprite atlas does not reflect the added sprites in the pack list, nor can I repack the atlas.

I’ve also made sure to update/save the atlas:

EditorUtility.SetDirty(atlas);
AssetDatabase.SaveAssets();

What is the correct code to add sprites to the sprite atlas?

You need to use the SpriteAtlasAsset class:


// load the SpriteAtlasAsset from asset path
var asset = SpriteAtlasAsset.Load(assetPath);
// add your images
asset.Add( objectsToAdd );
// save the modifications
SpriteAtlasAsset.Save( asset, assetPath );
// refresh the asset database
AssetDatabase.Refresh();