Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out if an SKTexture is the placeholder image

In SpriteKit, if you load an image with the [SKTexture textureWithImageNamed:] method, it will first search your bundles, then atlases, if it fails to find your texture, it will then create a placeholder image and load it.

Is there a way to find out (without visually checking) if the loaded image is a placeholder?

This doesn't seem like a very "cocoa" way to handle this type of error.

developer.apple.com is down now, so I figured I would pose this question to SO.

like image 417
Weston Avatar asked Apr 05 '14 01:04

Weston


2 Answers

You can check if the atlas contains the image. I created the following method in my AtlasHelper:

+(BOOL) isTextureWithName:(NSString *) name existsInAtlas:(NSString *)atlasName
{
    SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:atlasName];
    return [atlas.textureNames containsObject:name];
}
like image 65
Gal Marom Avatar answered Nov 03 '22 22:11

Gal Marom


SKTexture has some private properties that would be helpful (see e.g. https://github.com/luisobo/Xcode-RuntimeHeaders/blob/master/SpriteKit/SKTexture.h), but in Swift and during development I'm using this:

extension SKTexture {
    public var isPlaceholderTexture:Bool {
        if size() != CGSize(width: 128, height: 128) {
            return false
        }

        return String(describing: self).contains("'MissingResource.png'")
    }
}

Attention!:

This only works, if you are using a SKTextureAtlas:

let t1 = SKTextureAtlas(named: "MySprites").textureNamed("NonExistingFoo")
// t1.isPlaceholderTexture == true

let t2 = SKTexture(imageNamed: "NonExistingBar")
// t2.isPlaceholderTexture == false
like image 31
Klaas Avatar answered Nov 03 '22 23:11

Klaas