Search code examples
swiftsprite-kitskspritenode

How can I remove a subclass of SKSpriteNode from parent correctly in Swift (to be removed from array, space on screen...)?


I've created a subclass:

class EnemySprite: SKSpriteNode

and added an enemy in my game scene using this code:

let enemy = EnemySprite(imageNamed:"enemy.png")
self.addChild(enemy)

Now when I shoot on the enemy I have the code:

enemy.removeFromParent()

The enemy is not seen on the screen, but the _enemiesSpritesArray.count remains the same. Also, when I shoot to the area where the enemy was, bullets stop there as if the sprite is still in the same spot. I've tried to add:

override func removeFromParent() {
    super.removeFromParent()
}

but still the same.

How can I remove the sprite completely?


Solution

  • You should remove the instance from the array as well.

    if let index = enemiesSpritesArray.index(of: enemy) {
        enemiesSpritesArray.remove(at: index)
    }