Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the filename of an SKSpriteNode in Swift 3

How can I access the image filename from an SKSpriteNode? I have been trying to Google this, but no answer seems to be available. Here is the impotent part of my code:

current_ingredient?.name = String(describing: current_ingredient?.texture)

print("Filename: \(current_ingredient?.name)")

The print command returns this:

Filename: Optional("Optional(<SKTexture> \'ingredient14\' (110 x 148))")

So, the question is, how do I get only "ingredient14"?

like image 577
thar Avatar asked Dec 21 '16 21:12

thar


2 Answers

Saving inside userData

You can store the image name you used to create a sprite inside the userData property.

let imageName = "Mario Bros"
let texture = SKTexture(imageNamed: imageName)
let sprite = SKSpriteNode(texture: texture)
sprite.userData = ["imageName" : imageName]

Now given a sprite you can retrive the name of the image you used originally

if let imageName = sprite.userData?["imageName"] as? String {
    print(imageName) // "Mario Bros"
}
like image 88
Luca Angeletti Avatar answered Sep 21 '22 04:09

Luca Angeletti


It is stored in the description, so here is a nice little extension I made to rip it out.

extension SKTexture
{
    var name : String
    {
        return self.description.slice(start: "'",to: "'")!
    }
}

extension String {
    func slice(start: String, to: String) -> String? 
    {

        return (range(of: start)?.upperBound).flatMap 
        { 
          sInd in
            (range(of: to, range: sInd..<endIndex)?.lowerBound).map 
            {
                eInd in
                substring(with:sInd..<eInd)

            }
        }
    }
}
usage:

print(sprite.texture!.name)
like image 35
Knight0fDragon Avatar answered Sep 24 '22 04:09

Knight0fDragon