Search code examples
swiftsprite-kitskspritenodeuser-data

get userData of SKSpriteNode using the scene editor


I set the userData of my SKSpriteNode in the scene editor:

enter image description here

Then I tried to get it, using:

let sprite:SKSpriteNode = self.childNode(withName: "sprite") as? SKSpriteNode
let numero:Int = sprite.userdata?.valueForKey("numero") as! Int

But I got nil value : "fatal error: unexpectedly found nil while unwrapping an Optional value"

I also tried to init the userData with:

sprite.userData? = NSMutableDictionary()

But same result...


Solution

  • Probably also your sprite is nil:

    try to search your sprite with the optional binding (if let) and the "//" before sprite.

    if let sprite = self.childNode(withName: "//sprite") as? SKSpriteNode {
           let numero:Int = sprite.userdata?.valueForKey("numero") as! Int
    } else {
       print("I cannot find sprite..")
    }
    

    It performs a recursive search from its current position. Check the API reference here.