为什么我在 swift xcode 中出现此错误? "Attemped to add a SKNode which already has a parent"

Why do i get this error in swift xcode? "Attemped to add a SKNode which already has a parent"

我不知道为什么我总是收到此错误消息。你能看看我的代码并告诉我我做错了什么吗?由于某种原因,我在 arrowLeft 上收到错误。

由于未捕获的异常 'NSInvalidArgumentException',正在终止应用程序,原因:'Attemped to add a SKNode which already has a parent: name:'(null)' 纹理:[

class GameScene: SKScene, SKPhysicsContactDelegate {

let arrowLeft = SKSpriteNode(imageNamed: "leftarrow")
let arrowRight = SKSpriteNode(imageNamed: "rightarrow")

func moveArrowInstructions() {

    arrowLeft.position = CGPointMake(self.size.width / 4.0, self.size.height / 2)
    arrowLeft.zPosition = 20
    arrowRight.position = CGPointMake(self.size.width / 1.3, self.size.height / 2)
    arrowRight.zPosition = 20
    arrowLeft.setScale(0.4)
    arrowRight.setScale(0.4)

    arrowRight.alpha = 0
    arrowLeft.alpha = 0

    let moveArrowToRight = SKAction.moveByX(150 + arrowRight.size.width, y: 0, duration: 2.5)
    let moveArrowToLeft = SKAction.moveByX(-150 - arrowLeft.size.width, y: 0, duration: 2.5)
    let fadeInArrows = SKAction.fadeInWithDuration(1.0)
    let fadeOutArrows = SKAction.fadeOutWithDuration(1.0)
    let sequenceLeftArrow = SKAction.sequence([fadeInArrows, moveArrowToLeft, fadeOutArrows])
    let moveLeftArrowRepeat = SKAction.repeatActionForever(sequenceLeftArrow)
    let sequenceRightArrow = SKAction.sequence([fadeInArrows, moveArrowToRight, fadeOutArrows])
    let moveRightArrowRepeat = SKAction.repeatActionForever(sequenceRightArrow)

    arrowLeft.runAction(moveLeftArrowRepeat)
    arrowRight.runAction(moveRightArrowRepeat)




    addChild(arrowLeft)
    addChild(arrowRight)
}


    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

        func moveArrows() {

        let generateArrows = SKAction.sequence([
            SKAction.runBlock(self.moveArrowInstructions),
            SKAction.waitForDuration(3.5)])
        let endlessAction = SKAction.repeatActionForever(generateArrows)
        runAction(endlessAction)
    }

    var touch: UITouch = touches.first as! UITouch
    var location = touch.locationInNode(self)
    var node = self.nodeAtPoint(location)


    if(node.name == "startgame") {
        arrowRight.removeFromParent()
        arrowLeft.removeFromParent()






    }

您每次触摸 parent 都会不断添加相同的 child

添加孩子(向左箭头) addChild(arrowRight)

设置场景时需要在某个区域

您正在尝试多次将同一节点添加到场景中。

快速解决方法是检查节点是否已添加到场景中。像这样:

if arrowLeft.parent == nil && arrowRight.parent == nil{
   addChild(arrowLeft)
   addChild(arrowRight)
}