theloneswiftman
theloneswiftman

Reputation: 188

(Swift + Spritekit) - remove node and its data entirely

I'm working a little game for iOS.

I've a SKSpriteNode in my scene - when I remove it with "removeFromParent" and touch the area it was last in, I still get the function.

My code is as following:

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        if tapToPlayNode.containsPoint(location){
            tapToPlayNode.removeFromParent()
            startNewGame()
        }
    }
}

func startNewGame(){
    //Starts a new game with resetted values and characters in position
    println("Ready.. set.. GO!")

    //Shows the ui (value 1)
    toggleUiWithValue(1)
}

In other words, I get "Ready.. set.. GO!" output when I touch the area even after it was deleted.

Any clues?

Bests,

Upvotes: 3

Views: 9657

Answers (1)

bsarr007
bsarr007

Reputation: 1964

Your tapToPlayNode is still retained by self and is removed from it's parent. You should make it optional var tapToPlayNode:SKSpriteNode?and nil it after remove it from it's parent like this:

if let playNode = self.tapToPlayNode {
   for touch: AnyObject in touches {
   let location = touch.locationInNode(self)

        if playNode.containsPoint(location) {
            playNode.removeFromParent()
            startNewGame()
            self.tapToPlayNode = nil // il it here!
            break
        }
    }
}

You can also avoid to keep a reference of your tapToPlayNode and give it a name when initializing it like this:

node.name = @"tapToPlayNodeName"
// Add node to scene and do not keep a var to hold it!

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */

    // Retrieve the ode here
    let tapToPlayNode = container.childNodeWithName("tapToPlayNodeName")!
    for touch: AnyObject in touches {
       let location = touch.locationInNode(self)

        if tapToPlayNode.containsPoint(location){
            tapToPlayNode.removeFromParent()
            startNewGame()
        }
    }
}

Upvotes: 4

Related Questions