princearthur791 princearthur791 - 27 days ago 8
Swift Question

How can I get my SKNodes in different file from the gamescene swift

I couldn't find anything on having SKNodes in seperate files from the gamescene.swift. I tried writing this in a new class swift file but did not seem to work. I had to make a function but I did not know how to call it in my gamescene.

let testLabel = SKLabelNode(fontNamed: "AppleSDGothicNeo-Medium")
testLabel.text = "TEST"
testLabel.position = CGPoint(x: self.frame.midX, y: 300)
testLabel.fontSize = 90
testLabel.color = SKColor.blue
testLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center


I'm trying to make this in another swift file and only use the testlabel in my gamescene.

Thanks in advance.

Answer

Rather than creating a new file, you could consider creating a property for your label inside the GameScene.swift file. This lets you add the label to the scene by calling self.testLabel.

class GameScene: SKScene {
    lazy var testLabel: SKLabelNode! = {
        let testLabel = SKLabelNode(fontNamed: "AppleSDGothicNeo-Medium")
        testLabel.text = "TEST"
        testLabel.position = CGPoint(x: self.frame.midX, y: 300)
        testLabel.fontSize = 90
        testLabel.color = SKColor.blue
        testLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center

        return testLabel
    }()

    override func didMove(to view: SKView) {
        self.addChild(self.testLabel)
    }
}

It doesn't really make sense to create a new file, unless you want to create a custom SKLabelNode with some extended functionality.

Another approach could be to create a function that creates a label from input parameters.

class GameScene: SKScene {
    func makeTestLabel(text: String, position: CGPoint) -> SKLabelNode {
        let testLabel = SKLabelNode(fontNamed: "AppleSDGothicNeo-Medium")
        testLabel.text = text
        testLabel.position = position
        testLabel.fontSize = 90
        testLabel.color = SKColor.blue
        testLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center

        return testLabel
    }

    override func didMove(to view: SKView) {
        self.addChild(self.makeTestLabel(text: "Test1", position: CGPoint(x: self.frame.midX, y: 300)))
        self.addChild(self.makeTestLabel(text: "Test2", position: CGPoint(x: self.frame.midX, y: 400)))
    }
}
Comments