附加到它后Swift数组为空

时间:2014-06-24 04:43:53

标签: sprite-kit swift

首先是SO问题:)

我在Swift课堂上看到了奇怪的行为我正在写一篇关于在我正在研究的精灵套件游戏中展示玩家健康的文章。这是我的球员健康课:

class PlayerHealth : SKNode {
    let healthBlock: SKSpriteNode
    let padding: CGPoint = CGPoint(x: 280, y: 730)

    var health: Int
    var healthBlocks: SKSpriteNode[] = []

    init(health: Int) {
        self.health = health
        self.healthBlock = SKSpriteNode(color: SKColor.greenColor(), size: CGSizeMake(8, 8))
        super.init()
        for i in 0..5 {
            healthBlocks.append(self.healthBlock.copy() as SKSpriteNode)
            let pos = CGPointMake(padding.x + Float(i) * 10, padding.y)
            healthBlocks[i].position = pos
            self.addChild(healthBlocks[i])  // array is empty here, but that doesn't stop the spritenode from making it's way into the scene
        }
        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(self, selector: "deductHealth:", name: "playerDamaged", object: nil)
    }

    deinit {
        NSNotificationCenter
            .defaultCenter().removeObserver(self)
    }

    func deductHealth(amount: Int) {
        for i in 0..amount {

            // fails here, thinking that healthBlocks is empty
            let node = healthBlocks.removeLast()
            node.removeFromParent()
        }
    }

    func deductHealth(notification: NSNotification) {
        self.deductHealth(notification.object as Int)
    }
}

当我发布" playerDamaged"通知,它错误地认为healthBlocks为空。在init方法中检查healthBlocks也表明它是空的。这很奇怪,因为Sprite Node出现在场景中,尽管我将它作为healthBlocks中的一个元素引用。

编辑:当在XCode调试器中单步执行init方法时,似乎healthBlocks为空。使用println将值转储到控制台显示它确实包含内容。但是,在第一个扣除健康方法中调用healthBlocks.removeLast()时,我收到一条错误,指出该数组为空。

有没有人遇到过这个问题?我正在做的事情可能会导致healthBlocks数组为空吗?

1 个答案:

答案 0 :(得分:0)

我认为你对healthBlocks完全错误,为空,问题是amount不是你认为的那样,因为notification.object不是你想象的那样。

相关问题