Pablo
Pablo

Reputation: 1332

Changing the initial game scene in Swift

I want to change the initial scene being presented to be another class other than the default GameScene class. From reading other questions, I understand I must change this part from the GameViewController:

       if let scene = SKScene(fileNamed: "GameScene") {
            print(scene)
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }

So within the GameScene.swift file I am creating a new class:

class MainMenu : SKScene {
   override func didMove(to view: SKView) {
      print("At least it ran")
      self.scene?.view?.presentScene(GameScene())
   }
}

However, when I change the scene to:

if let scene = SKScene(fileNamed: "MainMenu")

When I run the project, it gets stuck, but when I run it with the string "GameScene" then it works perfectly. I am doing something wrong loading the MainMenu?

Upvotes: 0

Views: 502

Answers (1)

Ron Myschuk
Ron Myschuk

Reputation: 6061

In my opinion you should separate your scenes into their own files...

Do you have an corresponding SKS file for MenuScene? You need to create one if you are trying to load it with fileNamed:

  • or -

Use this code to load a SKScene file that is created in code only and not in the Scene editor

if let skView = self.view as? SKView {

    if skView.scene == nil {

        let scene = MenuScene(size: skView.bounds.size)        
        scene.scaleMode = .aspectFill
        skView.presentScene(scene)
    }
}

and then in your MenuScene file you will need an init func

init(size: CGSize) {

    super.init(size: size)

    name = "menuScene"
}

Upvotes: 1

Related Questions