Does Sprite Kit load a texture atlas multiple times if I use SKTextureAtlas later?

1.5k views Asked by At

This is making me think.

Game starts and I create sprites with -spriteNodeWithImageNamed: method. Later for animation, I create a SKTextureAtlas object. Some people say it is faster because -spriteNodeWithImageNamed: will first look in your app bundle for a png and after this it will look into the atlas.

But what is unclear to me: If I create a SKTextureAtlas later will this know about the already loaded atlas image or will it be dumb and just load the image again?

And if I create SKTextureAtlas object in multiple nodes for same atlas. Will it load the atlas multiple times? Must I make sure I use only one SKTextureAtlas instance for any atlas?

1

There are 1 answers

0
CodeSmile On

It's true that spriteNodeWithImageNamed: will look for the file in the bundle first. If it can't find a bundle file, it will check if an image with that name exists in an atlas available in the bundle.

If Sprite Kit finds an image with that name in any atlas, it will automatically load that atlas in order to use said image as the sprite when using the spriteNode/initWithImageNamed: initializers. This makes it easy to start developing without atlases and later adding files to an atlas.

I recommend to use atlases from the start because there can be subtle differences and you'll be able to assess the performance of your app more realistically.

Yes, Sprite Kit is clever enough to not reload a resource that is already in memory. It will also not create a new instance of the same atlas but rather it will return you the pointer to the already existing atlas of the same name.

Sprite Kit also employs a caching mechanism apparently, so even if the last strong reference to a resource file has been removed the file will remain in memory. However I don't think anyone has done an in-depth analysis of how and when and in what order Sprite Kit eventually releases cached instances from memory.

Long story short: rely on Sprite Kit to do the right thing for you.