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"?
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"
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With