There's a better approach to this problem than assigning tags like "spaceship" + counter
.
The Spaceship class
Yes, for a number of reasons you should create a Spaceship
class, like this
class Spaceship: SKSpriteNode {
init() {
let texture = SKTexture(imageNamed: "spaceship")
super.init(texture: texture, color: .clearColor(), size: texture.size())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Retrieving all the spaceships
class GameScene:SKScene {
var spaceships: [Spaceship] {
return self.children.flatMap { $0 as? Spaceship }
}
}
Why a custom class is better than "numbered tags"
For several reasons
- You don't get crazy assigning a new tag-with-counter value to each new sprite that should act like a Spaceship
- You can add behaviour to your spaceship entity simply adding methods to the Spaceship class.
- The compiler will block you if you erroneously use another node as a spaceship
- You code is cleaner