1

I have this code in SKScene:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {

    var touch: AnyObject = touches.anyObject()
    var point = getPoint(touch.locationInNode(self))
    var name  = NSStringFromCGPoint(point)

    for children in self.children {

        if (children as SKSpriteNode).name == name {

            println("exist!")
        }
    }
    var tempNode = self.childNodeWithName(name)
}

I see "exist!" in log, so there is a node with this name in children array, but tempNode is nil. The self.childNodeWithName("//" + name)call returns nil too.

Valeriy
  • 785
  • 2
  • 10
  • 28

2 Answers2

10

Here is how to accomplish this in Swift... Hope this helps!

var mySprite: SKSpriteNode = childNodeWithName("mySprite") as SKSpriteNode
Thomas Jeans
  • 398
  • 3
  • 4
  • childNodeWithName always failing with fatal error: unexpectedly found nil while unwrapping an Optional value – Alessandro Ornano Mar 29 '16 at 13:48
  • This could be due to a couple of things. There could be a typo in the name string or the node you're looking for might not yet have been initialized or might have already been removed when childNodeWithName is being called. Optional chaining is a good way to protect against this. Try this: `if let mySprite = childNodeWithName("mySprite") { // Do something with the node }` – Thomas Jeans Mar 30 '16 at 02:39
  • 1
    **Swift 4** var mySprite: SKSpriteNode = childNode(withName: "mySprite") as! SKSpriteNode – uplearned.com Mar 20 '18 at 23:39
0

I've found this strangeness using Swift 2.2, maybe a bug .. you can't use NSStringFromCGPoint and childNodeWithName without cleaning the string from braces:

Using this little method:

func removeBraces(s:String)->String {
    return s.stringByTrimmingCharactersInSet(NSCharacterSet.init(charactersInString: "{}"))
}

when you add your SKSpriteNode do for example:

...
mySpriteNode.name = removeBraces(NSStringFromCGPoint(mySpriteNode.position))
...

and to retrieve it for your case :

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {

    var touch: AnyObject = touches.anyObject()
    var point = getPoint(touch.locationInNode(self))
    var name  = removeBraces(NSStringFromCGPoint(point))
    if let child = self.childNodeWithName(name) {
        print("I've found: \(child)")
    }
    ...
}
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133