1
\$\begingroup\$
using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    public Sprite[] mySprites;

}

From the editor, you can put sprites in the array property.

I want to put several large sprites there, like, 20 huge ones. However, only one of the 20 will be used by a SpriteRenderer at any given moment (I just have them in an array so I can switch easily in the future).

My concern is performance: does having an array containing 20 "Sprite" references imply that Unity will load the texture data of all 20 sprites? Or will Unity only load the data for the sprite that will be used by SpriteRenderer smartly?

\$\endgroup\$
1
\$\begingroup\$

When you put anything in an array it's going to be in memory. So yes, it will load all 20 sprites.

However, the sprite renderer will only be rendering the sprite it has a target to, so you don't get any increased performance overhead CPU/GPU wise.

It does take more time to load 20 sprites compared to 1 sprite, but as long as this loading is done once and not multiple times in a short period, you shouldn't need to worry about performance issues. Also, twenty textures isn't a lot, unless they're super huge.

\$\endgroup\$
  • \$\begingroup\$ Do note, that if you set the packing tag on your sprites (to the same), Unity will attempt to pack them together in an atlas, which will reduce the asset to fewer or just 1 texture. \$\endgroup\$ – Nicki Feb 1 '17 at 20:37
1
\$\begingroup\$

Sprite holds a reference to a texture. It is not a texture itself. Therefore, if you have 20 sprites using the same texture, it will only load the 1. Textures are resources, and should only be referenced, not copied.

http://docs.unity3d.com/ScriptReference/Sprite.html

Read about it here.

\$\endgroup\$
  • \$\begingroup\$ So the memory consumption will be the same regardless of how large my sprite array is, because only one is loaded at a time? If I change the SpriteRenderer's sprite property, the new sprite will be loaded - and I guess that the old one is unloaded (or does it remain cached so it won't take up the time to load again?) \$\endgroup\$ – Oxide Nov 3 '14 at 6:57
  • \$\begingroup\$ You'll have the memory overhead of each sprite class. But the texture will not be duplicated in memory. Sprite just holds a reference to a texture. \$\endgroup\$ – Ben Nov 3 '14 at 9:17
  • \$\begingroup\$ If they're all using the same texture, then yes that texture is only loaded once. However I don't think that's what the question is asking (admittedly, it's not specified). Asking about "the texture data of all 20 sprites" sounds to me like separate images. Unity preloads all referenced assets; avoiding that is a major reason why Resource.Load() even exists. \$\endgroup\$ – jhocking Nov 3 '14 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.