Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving and Reading information from a Sprites UserData

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 :(")
    }
}
like image 935
Peter L Avatar asked Mar 31 '16 03:03

Peter L


1 Answers

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.

like image 117
Skyler Lauren Avatar answered Nov 16 '22 10:11

Skyler Lauren