Avoid Subclassing SKSpriteNode
When I see SpriteKit questions on Stack Overflow, I notice a common problem people make. They make every visible entity in their game, such as the player and enemies, a subclass of SKSpriteNode
. They also add a property to the subclass for the sprite node.
class Player: SKSpriteNode {
var sprite: SKSpriteNode
}
Subclassing SKSpriteNode
and having a property of SKSpriteNode
is redundant. If you have a property for the sprite, you don’t need to subclass SKSpriteNode
. If you have a SKSpriteNode
subclass, an instance of the subclass has all the components of SKSpriteNode
. You don’t need the property.
In 99 percent of cases, avoid subclassing SKSpriteNode
and add a property for the sprite node to your class or struct. Prefer composition to inheritance.
class Player {
var sprite: SKSpriteNode
}
A player has a sprite node along with other properties that depend on your game (score, number of lives, health, etc.). A player is not a sprite node.