I'm trying to have a value be saved onto a sprite's user data and be able to read it off.
Heres what I have, for some reason the value never gets saved and stays as nil.
import SpriteKit
let frame = SKScene()
func createSprite() {
let sprite = SKSpriteNode()
sprite.userData?.setValue("100", forKeyPath: "key")
frame.addChild(sprite)
}
createSprite()
for child in frame.children where child is SKSpriteNode {
print(child.userData?.valueForKey("key") as? String)
//prints the value saved in the childs user data
if child.userData?.valueForKey("key") as? String == "100" {
print("It was a Success!")
}
if child.userData?.valueForKey("key") as? String == nil {
print("There was a problem :(")
}
}
I believe your issue is that the userData starts out as nil. Try this...
func createSprite() {
let sprite = SKSpriteNode()
//init NSMutableDictionary
sprite.userData = NSMutableDictionary()
sprite.userData?.setValue("100", forKeyPath: "key")
frame.addChild(sprite)
}
Hopefully that helps.
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