Peter L Peter L - 4 years ago 181
Swift Question

Target Multiple Sprites Based on their Name?

The problem with this code is that it's only targeting 1 SKNode named "coin", I want to target all SKNodes named "coin". I'm not sure how to do this...

Heres what I have:

func killCoins(){
let skcoin: SKNode = self.childNodeWithName("coin")!
// Looks for a SKNode named "coin".
let coinsprite: SKSpriteNode = (skcoin as? SKSpriteNode)!
// Converts the SKNode into a SKSpriteNode
coinsprite.removeFromParent()
// Kills Sprite
}

Answer Source

To remove multiple SKSpriteNodes, loop through all of the children and remove those SKSpriteNodes with the name "coin".

func killCoins() {
    for child in self.children where child is SKSpriteNode {
        if child.name == "coin" {
            child.removeFromParent()
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download