Search code examples
swift3texturepackersktexturetexture-atlassktextureatlas

Can SKTextureAtlas load bundle from "my" bundle instead of "host" bundle?


I'm working on a SWIFT3/SpriteKit screensaver and I had the screensaver working except I cannot get my texture to load because when I do the following:

// load texture atlas
let textureAtlas = SKTextureAtlas(named: "Flyers")

The SKTextureAtlas is looking for the "Flyers" in the main bundle which when running inside of the screensaverengine.app, that is not the bundle where the textures live.

In my old obj-c based screensaver, I had to do the following to load images from the bundle:

thisBundle = [NSBundle bundleForClass:[self class]];
fileName=[[NSString alloc ] initWithFormat:@"flyer%d", flyNum];
picturePath = [thisBundle pathForResource:fileName ofType:@"png"];
flyerImage= [[NSImage alloc ] initWithContentsOfFile:picturePath];

Before I go the route of loading the images and creating the textures at runtime, I wanted to tap the Stackoverflow family for some help... thoughts?


Solution

  • I've never used SpriteKit.

    But looking at the documentation, starting from iOS 8, you can use UIImage(named: imageName, in: bundle, compatibleWith: nil) to get images from any bundle, then easily instantiate your atlas with a dictionary of those images:

    let bundle = Bundle(for: type(of: self))
    var dictionary = [String:Any]()
    ["textureName": "imageName"].forEach { textureName, imageName in
        dictionary[textureName] = UIImage(named: imageName, in: bundle, compatibleWith: nil)
    }
    let atlas = SKTextureAtlas(dictionary: dictionary)