Trouble using SKReferenceNode programmatically

268 views Asked by At

I'm planning to make an arcade game in which the screen is divided in two halves. Each of this half's background can vary each time the player starts the game.

I wanted to design my backgrounds into different .sks files, and then randomly load two of them into my GameScene by using the SKReferenceNode programmatically.

The trouble is that the sks content is treated as an SKScene, and so it obviously can't be added as a child of my scene:

class GameScene: SKScene {
    override func didMove(to view: SKView) {
        let upperBackground = SKReferenceNode(fileNamed: "Caribbeans")!
        addChild(upperBackground)
    }
}

I'm wondering if there's a way to make the compiler treat my SKReferenceNode as a SKSpriteNode, but trying to downcast doesn't work since SKReferenceNode and SKSpriteNode are unrelated.

I know that it works whenever I create a bigger sks scene, drag two SKReferenceNodes and then set their references to a single background, but the problem is that I want to make a random selection of two backgrounds that vary each time, so I must find a way to get around this trouble programmatically and not through the scene editor.

Any suggestions?

1

There are 1 answers

0
gionti On BEST ANSWER

As I mentioned in another post, I found a workaround.

In my case, I substituted the SKReferenceNode with an SKScene.

I first made sure that, in my .sks scene, all SKSpriteNodes were children of one main node. It doesn't have to be a direct link, you can still respect the hierarchies of your scene, but it's important that at the end of the "hierarchy tree" they are linked to one node, which in my case is the background, but it can also be an empty node.

enter image description here

In my GameScene file I then wrote the following code:

class GameScene: SKScene {
    var mainNode: SKNode? = nil
    override func didMove(to view: SKView) {
        var mySksScene = SKScene(fileNamed: "Caribbeans")
        mainNode = upperBackground?.childNode(withName: "backgroundCaribbean")
        mainNode?.removeFromParent()
        mySksScene = nil
        addChild(mainNode)
    }
}

I first declared an optional SKNode variable. Then, inside didMove(:to:), I loaded my .sks file in an optional SKScene() variable. I then set SKNode as the main node, the node which is the parent of all the other nodes (in my case: backgroundCaribbean). I then removed my mainNode from its parent scene, THEN set to nil the variable that used to contain the .sks scene, and only THEN I added my mainNode as a Child of my GameScene.