Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How to get the memory usage of a SpriteAtlas during runtime.

Discussion in '2D' started by rekcah1986, Nov 8, 2023.

  1. rekcah1986

    rekcah1986

    Joined:
    Nov 23, 2017
    Posts:
    6
    And pixel size etc.
     
  2. sildeflask

    sildeflask

    Joined:
    Aug 16, 2023
    Posts:
    329
    cant get the memory usage easily

    u will have to use the memory profiler
     
  3. MartinTilo

    MartinTilo

    Unity Technologies

    Joined:
    Aug 16, 2017
    Posts:
    2,408
    Profiler.GetRuntimeMemorySizeLong(yourSpriteAtlas);

    But only in development builds.
     
  4. rekcah1986

    rekcah1986

    Joined:
    Nov 23, 2017
    Posts:
    6
    How about this:
    Code (CSharp):
    1.  
    2. public long GetAtlasMemory(SpriteAtlas atlas)
    3. {
    4.     var sprites = new Sprite[atlas.spriteCount];
    5.     atlas.GetSprites(sprites);
    6.     // Only take one because they are all the same
    7.     var texture = sprites[0].texture;
    8.     // Each pixel in the texture uses 4 bytes for RGBA color channels
    9.     var size = (long)(texture.width * texture.height * 4);
    10.  
    11.     // If using ASTC compression, consider the compression ratio
    12.     // For example, ASTC 4x4 typically provides a 4:1 compression ratio
    13.     // Adjust the size accordingly for ASTC compression
    14.     // size = (long)(size * compressionRatio);
    15.  
    16.     // Increase by 1/3 when Mipmap is enabled
    17.     size = (long)(size * 1.333);
    18.     return size;
    19. }
    20.  
     
  5. sildeflask

    sildeflask

    Joined:
    Aug 16, 2023
    Posts:
    329
    well this will give you how much memory it should be taking in theory

    this doesnt interact with any memory at all, its just a good guess.
    imagine there was some bug and it was taking 1gb, this math wouldnt get you anywhere
     
  6. MartinTilo

    MartinTilo

    Unity Technologies

    Joined:
    Aug 16, 2017
    Posts:
    2,408
    The Memory Profiler Module documentation covers which stats you can get in what kind of builds, including at runtime, and if they are available in non-development players (second table on the page). In your case, if sprites is practically all the textures you use, the best approximation might be to get the overall
    "Texture Memory"
    and
    "Texture Count"
    profiler counters via the ProfilerRecorder API, though that stat is only available in development builds.