for 循环中 addChild 的时间延迟导致错误! Swift

Time delay for addChild in for loop is causing error! Swift

我的这个循环工作正常,但我想让阵列中的图像一个接一个地进入,并且它们之间有特定的设定时间量。

if transitionSprite.name == nil || transitionSprite.name == "rd-d2c" || transitionSprite.name == "rd-f2c" {
        for (index, roadImage) in cityArrays[randomIndex].enumerated() {

            roadSprite = SKSpriteNode(imageNamed: roadImage)
            roadSprite.anchorPoint = CGPoint(x: 0.5, y: 0.5)
            roadSprite.position = CGPoint(x: 0, y: CGFloat(screenCounter) * roadSprite.size.height)
            roadSprite.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.size.width, height: self.size.height))
            roadSprite.physicsBody?.categoryBitMask = PhysicsCategory.RoadImageCategory.rawValue
            roadSprite.physicsBody?.collisionBitMask = PhysicsCategory.NoCollisionsCategory.rawValue
            roadSprite.physicsBody?.contactTestBitMask = PhysicsCategory.BroomCategory.rawValue
            roadSprite.physicsBody?.affectedByGravity = false

            roadSprite.zPosition = 1
            roadSprite.name = "Road \(index)"

            // RUNNING THE SKACTION DELAY ON THIS
            self.addChild(roadSprite)

            addCollectables()
            addJerryCans()

            if roadImage == "rdc-02_05" {
                addBackgroundDetail(detailType: "cityBridge2")
            }
            screenCounter += 1
        }

我创建了这个 SKAction,并将其添加到循环中,

    loopDelay = SKAction.wait(forDuration: Double(index + 1))
    let addRoad = SKAction.run {self.addChild(self.roadSprite)}
    let action = SKAction.sequence([loopDelay, addRoad])
    self.run(action)

不确定是什么原因导致的,但是当我 运行 它和我创建的 SKAction 延迟时它崩溃并给我这个错误,

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Attemped to add a SKNode which already has a parent: 
<SKSpriteNode> name:'Road 4' texture:[<SKTexture> 'rdc-02_05' (750 x 
1334)] position:{0, 6670} scale:{1.00, 1.00} size:{750, 1334} 
anchor:{0.5, 0.5} rotation:0.00'

关于为什么延迟会导致这种情况的任何想法?谢谢

您的问题是您使用 属性 存储 roadSprite。因此,在 for-in 循环的每次迭代中,您都将 属性 中存储的内容替换为新的 Sprite。

当每次延迟过去时,他们都会尝试使用相同的 Sprite(这是您最后创建的 Sprite)添加 addChild,因此第一次添加它,第二次它给您上面的错误:"Attempted to add a SKNode which already has a parent".

您在这里想要的是将精灵创建为局部变量,并在 SKAction.run 闭包中捕获该变量:

let roadSprite = SKSpriteNode(imageNamed: roadImage)

...

let addRoad = SKAction.run {self.addChild(roadSprite)} //capture the local variable in your closure here

如果您仍然想要引用所有这些 Sprites,那么也许您应该将它们粘贴到一个数组中而不是覆盖相同的 属性。