Texture preload in SpriteKit

I did some research and I can’t find anything that clearly explains how to preload both individual textures and textures in the animation. I am currently using Atlas in Assets.xcassets to group related animated images. Does my atlas image have them preloaded? Regarding single images, it makes sense to declare a texture before GameScene as follows: let laserImage = SKTexture(imageNamed: "Sprites/laser.jpg") , and then (for example) in one of my SKSpriteNode subclasses, can I just pass laserImage through?

Ultimately, I wanted to know if you have a specific way around this, or if I just have to store each texture as a constant until GameScene . Any advice on the right (and most effective) way to get around this would be great.

+7
ios swift preload sprite-kit textures
source share
2 answers

One satin with one texture

Put all your assets in one Sprite Atlas. If they do not fit, try at least putting all the assets of the same scene in one Sprite atlas

Preload

If you want, you can preload the texture atlas into memory using this code

 SKTextureAtlas(named: "YourTextureAtlasName").preloadWithCompletionHandler { // Now everything you put into the texture atlas has been loaded in memory } 

Automatic caching

You do not need to keep a link to the texture atlas; SpriteKit has an internal caching system. Let it do the job.

What name should I use to link to my image?

Forget the image file name, the name that you assign to the image in the Asset Catalog is the only name you need.

enter image description here

How to create a sprite from an image in a texture atlas?

 let texture = SKTextureAtlas(named:"croc").textureNamed("croc_walk01") let croc = SKSpriteNode(texture: texture) 
+6
source share

I tried to implement the appzYourLife answer, but increased the load time of each texture. So I put all the most used Sprites in one atlas and put it in a singleton.

 class Assets { static let sharedInstance = Assets() let sprites = SKTextureAtlas(named: "Sprites") func preloadAssets() { sprites.preloadWithCompletionHandler { print("Sprites preloaded") } } } 

I call Assets.sharedInstance.preloadAssets() in menuScene. AND:

 let bg1Texture = Assets.sharedInstance.sprites.textureNamed("background1") bg1 = SKSpriteNode(texture: bg1Texture) 

to reference a texture already loaded into memory.

+9
source share

All Articles