Search code examples
iosswiftsprite-kitskscene

Change the initial scene in spritekit swift 3


how to change initial scene in new xcode3? I found lots of instructions, but all of it working with this code:

extension SKNode {
  class func unarchiveFromFile(file : String) -> SKNode? {
    if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
        var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
        var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)

        archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
        let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! MenuScene
        archiver.finishDecoding()
        return scene
    } else {
        return nil
    }
}

}

But new Xcode project, GameViewController not contain this part of code and when I try to copy, it not work. So I make MainScene.swift and MainScene.sks and want to set these scene to main. What next?

Thanks!!!!


Solution

  • If you are using an .sks file for your scene layouts use the following code.

    override func viewDidLoad() {
    
        super.viewDidLoad()
    
        if let view = self.view as! SKView? {
    
            // Load the SKScene from 'MainScene.sks'
            if let mainScene = MainScene(fileNamed: "MainScene")  {
    
                // Set the scale mode to scale to fit the window
                mainScene.scaleMode = .aspectFill
                // Present the scene
                view.presentScene(mainScene)
            }
    
            view.showsFPS = true
            view.showsDrawCount = true
            view.showsNodeCount = true
            view.showsPhysics = true
            view.showsDrawCount = true
        }
    }