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

标签 xcode swift skaction

我不知道为什么我一直收到此错误消息。你能看看我的代码并告诉我我做错了什么吗?由于某种原因,我在 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)
}

关于xcode - 为什么我在 swift xcode 中会出现这个错误? "Attemped to add a SKNode which already has a parent",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29580116/

相关文章:

swift - 如何检测SKAction是否正在运行

ios - 如何使用计时功能缓慢加速 SpriteKit 的缩放功能

iphone - 链接至 iTunes 评级页面

ios - Xcode Obj-C 无法打开输出文件进行写入,架构 x86_64 的 errno=21

swift - UIRefreshControl 故障与自定义 TableViewCell 相结合

ios - 核心图形和渐变

ios - 使用 Assets 目录是否适用于应用程序中的所有图像或仅适用于图标/启动图像

ios - 如何在 iOS + Swift 中关闭我的应用程序的互联网访问

swift - 如何启用链接以在 WebView 的默认浏览器中打开

swift - SKLabelNode 在指定时间显示文本