Search Unity

What is the best practice to unload a SpriteAtlas?

Discussion in '2D' started by the-forty-seven, Sep 5, 2019.

  1. the-forty-seven

    the-forty-seven

    Joined:
    Nov 12, 2014
    Posts:
    6
    Hi,

    I load SpriteAtlases from the AssetBundle when the SpriteAtlasManager.atlasRequested has been raised.

    But I don't know when I should unload the loaded atlases. How can I catch the proper time when the atlas is no longer used?

    My custom code is like belows.

    Thanks in advance.

    Code (CSharp):
    1.  
    2.  
    3. Dictionary<string, SpriteAtlas> _atlases;
    4.     void Start()
    5.     {
    6.         _atlases = new Dictionary<string, SpriteAtlas>();
    7.         SpriteAtlasManager.atlasRequested += AtlasRequested;
    8.     }
    9.  
    10.     void AtlasRequested(string tag, Action<SpriteAtlas> callback)
    11.     {
    12.         StartCoroutine(CoLoadAtlas(tag, callback));
    13.     }
    14.  
    15.     IEnumerator CoLoadAtlas(string tag, Action<SpriteAtlas> callback)
    16.     {
    17.         if (!_atlases.ContainsKey(tag))
    18.         {
    19.             // load atlas from AssetBundles
    20.             AtlasLoadOperation req = LoadAtlasAsync(tag);
    21.             yield return req;
    22.             _atlases.Add(tag, req.Atlas);
    23.         }
    24.  
    25.         callback(_atlases[tag]);
    26.     }
    27.  
    28.     // When should I call this?
    29.     void UnloadAtlas(string tag)
    30.     {
    31.         if (_atlases.ContainsKey(tag))
    32.         {
    33.             Resources.UnloadAsset(_atlases[tag]);
    34.             _atlases.Remove(tag);
    35.         }
    36.     }
    37.