Search code examples
iosswiftsprite-kittexturespreload

Preloading textures in SpriteKit


I've done some research and I can't seem to find anything that clearly explains how to go about preloading both single textures and textures within animations. I'm currently using Atlas's in Assets.xcassets to group related animation images. Does having my images in the Atlas mean that they are preloaded? As far as single images, does it make sense to declare the texture before GameScene like this: let laserImage = SKTexture(imageNamed: "Sprites/laser.jpg") and then (for example) within one of my SKSpriteNode subclass I can just pass laserImage through?

I ultimately wanted to know if there was a well defined way of going about this or if I should just store each texture as a constant before GameScene. Any advice on the proper (and most efficient) way of going about this would be great.


Solution

  • One Single Texture Atlas

    Put all your assets into a single Sprite Atlas. If they don't fit, try at least to put all the assets of a single scene into a single Sprite Atlas

    Preloading

    If you want you can preload the texture atlas in memory with this code

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

    Automatic caching

    You don't need to save a reference to the texture atlas, SpriteKit has an internal caching system. Let it do it's job.

    Which name should I use to reference my image?

    Forget the name of the file image, the name you assign to the image into Asset Catalog is the only name you will need.

    enter image description here

    How can I create a sprite from an image into a texture atlas?

    let texture = SKTextureAtlas(named:"croc").textureNamed("croc_walk01")
    let croc = SKSpriteNode(texture: texture)