SpriteKit Scene referenced with SKReferenceNode does not load custom class

466 views Asked by At

I have a GameScene.sks a custom class GameScene.swift which is connected via the Custom Class Inspector (on the right in Xcode). This is working fine.

Now in the GameScene.swift where I want to reference another scene that I want to reuse in many scenes in the future (oversimplified code):

class GameScene: SKScene {
  // ...
  override func didMove(to view: SKView) {
    //...

    guard let gameMenuPath = Bundle.main.path(
      forResource: "GameMenu", ofType: "sks") else { return }

    let url = NSURL(fileURLWithPath: gameMenuPath) as URL
    let gameMenu = SKReferenceNode(url: url)

    addChild(gameMenu)

    //...

where I am loading a reusable GameMenu.sks.

Everything works fine till here. Now the custom class issue for the GameMenu.sks (the scene to be reused). For the GameMenu.sks I also have a GameMenu.swift which is referenced in the custom class inspector as custom class. So exactly as for the GameScene. The problem is that it seems like the GameMenu.swift is not found/loaded. I get no error - so it looks like I misspelled the custom class - but I checkt it many times and also cleared the Xcode cache.

Any ideas how to set custom class for a scene (.sks) that is referenced in another scene?

I would think this is something that is done for reusable scene parts suche as the GameMenu in my case that is visible in every GameScene.

Thank you for any hints.

2

There are 2 answers

1
iqra On

Is it necessary to add GameMenu in GameScene via code? You can also simply use the inspector. In your GameScene.sks drop the 'Reference' (SKReferenceNode) object. Select it from the hierarchy and select GameMenu as in the 'reference' dropdown.

enter image description here

5
Knight0fDragon On

SKReferenceNodes behave as nodes, not as scenes, which may cause confusion since you are creating a scene file.

This means none of the functions that a view calls on a scene will be called.

If you need some of these functions to call, you need to do it manually.

Look at this example to get your didMoveToView to fire:

override func didMove(to view: SKView) {

    let gameMenu = SKReferenceNode(fileNamed:"GameMenu") as? SKScene // (or your custom class)

    addChild(gameMenu)
    gameMenu.didMove(to:view)
 }