Abdou023
Abdou023

Reputation: 1664

Error creating a copy of a subclass

I have a basic enemy class that is a subclass of SKSpriteNode, I have another subclass of it. In my GameScene when I try to initialize an object from that subclass everything works perfectly, but when I try to create a copy of that object I get an error:

fatal error: use of unimplemented initializer 'init(texture:color:size:)'

that error refers to the basic class Enemy not the subclass EnemyA

Enemy basic class:

class Enemy: SKSpriteNode {

    init(image: String, health: Int, damage: CGFloat, moveSpeed: CGFloat){
        let texture = SKTexture(imageNamed: image)

        super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())

    }

EnemyA subclass:

class EnemyA: Enemy {

    override init(image: String, health: Int, damage: CGFloat, moveSpeed: CGFloat) {
        super.init(image: image, health: health, damage: damage, moveSpeed: moveSpeed) 
    }

creating the clone in GameScene:

        let enemyA = EnemyA(image: "Enemy_Sprite0", health: 10, damage: 20, moveSpeed: 5)

        let clone = enemyA.copy() as! SKSpriteNode
        clone.position = CGPoint(x: size.width / 2, y: size.height / 2)
        addChild(clone)

Upvotes: 0

Views: 124

Answers (1)

Eric
Eric

Reputation: 291

I had a similar issue of trying to copy a subclass of an SKSpriteNode. My solution was to override the copy() function (in the subclass). In that overridden copy() function I called /used the subclass's custom initializer -- my custom initializer calls super.init(texture:color:size). Passing in the necessary init parameters in the subclassed copy seems to do the trick.

Upvotes: 1

Related Questions