Swift addChild from Custom Class

377 Views Asked by At

i have a problem.

I made swift custom class test.swift and want to add a sprite from this Class to the the GameScene.swift

This is my custom Class

import SpriteKit
import GameplayKit

var scene = GameScene()


class test: SKSpriteNode{


    func test_function(){

        let mysprite = SKSpriteNode(imageNamed: "spark3")
        mysprite.name="sparkle4"
        mysprite.position = CGPoint(x: frame.midX, y: frame.midY)
        mysprite.setScale(8)
        mysprite.zPosition=2
        self.scene?.addChild(mysprite)


}


}

In the GameScene i call this function with

var new_class = test()

new_class.test_function()

but the sprite is not displayed in the app and i see no errors.

If i copy the function direct in the GameScene it worked.

Can anyone help me what i do wrong?

Thanks alot

2

There are 2 best solutions below

0
On

Because self.scene? is nil inside the subclass , while it's not inside GameScene , a node gets it's scene? assigned after you add it as a child to a scene

self.scene?.addChild(mysprite)

//

So you may do it like this

let tes = test()
self.scene?.addChild(tes)
tes.test_function()
0
On

I would restructure the class like this:

import SpriteKit

class test: SKSpriteNode {
    convenience init(n: String) {
        self.init(imageNamed: n)
        self.name="sparkle4"
        self.setScale(8)
        self.zPosition=2
    }

    override init(texture: SKTexture!, color: UIColor, size: CGSize) {
        super.init(texture: texture, color: color, size: size)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

so that you can create other instances more easily. Then in GameScene.swift, execute:

let mySprite = test(n: "spark3")
mySprite.position = CGPoint(x: frame.midX, y: frame.midY)
self.scene?.addChild(mysprite)

You are getting an error because scene is nil in your function, thus it can not be added to any scene.