Saving and Reading information from a Sprites UserData
Asked Answered
T

1

5

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 :(")
    }
}
Tuyere answered 31/3, 2016 at 3:14 Comment(0)
G
9

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.

Godunov answered 31/3, 2016 at 3:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.