(Swift + Spritekit) - 完全删除节点及其数据

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

我正在为 iOS 制作一个小游戏。

我的场景中有一个 SKSpriteNode - 当我用 "removeFromParent" 删除它并触摸它最后所在的区域时,我仍然可以使用该功能。

我的代码如下:

    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)
}

换句话说,当我触摸该区域时,即使它已被删除,我也会得到 "Ready.. set.. GO!" 输出。

有什么线索吗?

最佳,

您的 tapToPlayNode 仍由自己保留,并已从其父项中删除。 你应该让它成为可选的 var tapToPlayNode:SKSpriteNode? 并且在将它从它的父级中删除之后将它设为零:

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
        }
    }
}

您还可以避免保留对 tapToPlayNode 的引用,并在初始化时为其命名:

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()
        }
    }
}