Skip to main content
 首页 » 编程设计

xcode之为什么我在 swift xcode 中会出现这个错误 "Attemped to add a SKNode which already has a parent"

2024年01月01日60zhengyun_ustc

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

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'试图添加一个已经有父级的 SKNode:名称:'(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() 
 
 
 
 
 
 
    } 

请您参考如下方法:

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

快速修复可能是检查节点是否已添加到场景中。像这样:

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