19.4 C
New York
Thursday, September 4, 2025

unity – Ought to I destroy dynamically created Picture.sprite?


Simply to present this previous query a particular reply:

Sure, it is best to destroy dynamically-created Sprite situations while you’re performed with them.

How can we verify this?

Add a script like this to your scene. This creates 50 new random sprites each body.

public class SpriteTester : MonoBehaviour
{
    public Texture2D tex;
    Sprite[] _sprites = new Sprite[50];

    // Replace is known as as soon as per body
    void Replace()
    {
        for (int i = 0; i < _sprites.Size; i++)
        {
            // DestroyImmediate(_sprites[i]);
            _sprites[i] = Sprite.Create(
                tex,
                new Rect(Random.Vary(0, 50), Random.Vary(0, 50), Random.Vary(1, 50), Random.Vary(1, 50)),
                new Vector2(Random.Vary(0, 50), Random.Vary(0, 50))
            );
        }
    }
}

Open the Unity profiler by going to Window > Evaluation > Profiler and run your scene. You will see the “Complete Used Reminiscence” creeping up slowly from the reminiscence we’re allocating for all these sprites.

Now uncomment this line:

DestroyImmediate(_sprites[i]);

This releases the reminiscence related to the previous sprite earlier than we allocate a brand new one. Run your scene once more, and you may see “Complete Reminiscence Used” stops climbing.

There’s nonetheless some rubbish collector churn although (about 2 KB for 50 sprites, or ~40 bytes per sprite), so this is not free – keep away from creating and destroying sprites ceaselessly when you can moderately cache/reuse them as a substitute. However when you solely want to do that sometimes, like throughout a stage transition or when loading a mod, user-generated content material, or different asset you’ll be able to’t predict upfront, 40 bytes per sprite will not break the financial institution. Simply keep in mind to destroy it while you’re performed with it!


What I need to reveal with this reply is not only whether or not we should always destroy sprites, however that each time you’ve any query about what prices extra time or reminiscence, the easiest way to reply that query is to profile it. It is typically very straightforward to take action – this instance solely took a couple of dozen traces of code and 5 minutes to check. Writing the textual content of the reply took extra time and thought. 😉

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles