2

So it appears in the profiler that whenever one of our sprite animations is played for the first time, it causes a spike on the CPU as the sprite atlases are loaded into memory. This can cause a noticeable performance issue when multiple of these sprites are trying to be read and loaded. So I assume the best way would be to cache the sprites at the start of the scene but there doesn't appear to be any way to do that that'll consistently work properly, especially for sprite atlases.

Are there any ways to preload a sprite atlas or sprites used in a sprite animation so that it doesn't cause these horrible CPU spikes?

enter image description here

1 Answer 1

1

When a sprite is first accessed in Unity, Unity "lazy loads" the textures and metadata, and this causes the spikes in your CPU. The easiest way for you to avoid this would be to load the asset at the start of the game. This forces Unity to load the atlas into memory, so when you activate it it will just read it from memory, and you won't have spikes since reading is a lighter operation than loading:

[SerializeField] private Sprite[] preloadSprites;

void Start()
{
    foreach (var sprite in preloadSprites)
    {
        var temp = sprite.texture;
    }
}

If you don't want to reference the Sprites in a script, you can place them under a Resources folder and load them at start like this:

void Start()
{
    var allSprites = Resources.LoadAll<Sprite>("Path/To/Sprites");
    foreach (var sprite in allSprites)
    {
        var temp = sprite.texture;
    }
}

As a final suggestion, if you are using a dynamic sprite atlas and want more grained control over it, you can use Unity's SpriteAtlasManager.

Sign up to request clarification or add additional context in comments.

2 Comments

This seems to actually prevent the Loading.ReadObject spike which is fantastic. However it brings up the concern about tanking the memory by loading so many sprite atlases to it. Is that just one of the downsides to using this method or are there ways around it?
Unfortunately there is no direct way around it. But you can use both to prevent spikes and bloated memory allocation by splitting atlases or loading sprites in asynchronous threads

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.