Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

SpriteAtlas resizing via script

Discussion in '2D' started by mandarin, Oct 17, 2017.

  1. mandarin

    mandarin

    Joined:
    Dec 8, 2009
    Posts:
    21
    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
     
  2. mandarin

    mandarin

    Joined:
    Dec 8, 2009
    Posts:
    21
    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:

    Code (CSharp):
    1.  
    2. SpriteAtlas masterAtlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(masterPath);
    3. SpriteAtlas variantAtlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(variantPath);
    4.  
    5. Assembly editorAssembly = Assembly.GetAssembly(typeof(Editor));
    6. Type spriteAtlasExt = editorAssembly.GetType("UnityEditor.U2D.SpriteAtlasExtensions");
    7. Type spriteAtlasUtil = editorAssembly.GetType("UnityEditor.U2D.SpriteAtlasUtility");
    8.  
    9. spriteAtlasExt
    10.     .GetMethod("SetIsVariant")
    11.     .Invoke(variantAtlas, new object[] { variantAtlas, true });
    12.  
    13. spriteAtlasExt
    14.     .GetMethod("SetMasterAtlas")
    15.     .Invoke(variantAtlas, new object[] { variantAtlas, masterAtlas });
    16.  
    17. spriteAtlasExt
    18.     .GetMethod("SetVariantMultiplier")
    19.     .Invoke(variantAtlas, new object[] { variantAtlas, scale });
    20.  
    21. spriteAtlasUtil
    22.     .GetMethod("PackAtlases", BindingFlags.Static | BindingFlags.NonPublic)
    23.     .Invoke(null, new object[] {
    24.         new SpriteAtlas[] { variantAtlas },
    25.         EditorUserBuildSettings.activeBuildTarget
    26.     });
    27.  
    You can have a look at the source code for the UnityEngine.U2D namespace at https://github.com/MattRix/UnityDec...3c81bc0910cef177c/UnityEditor/UnityEditor.U2D