Search code examples
iosswiftsprite-kitskscene

How do I set the initial scene in a sprite kit project?


I have two SKScenes GameScene and MenuScene and the default scene that appears when i open the app is the GameScene but I want MenuScene to appear first

I tried to change the code in GameViewController:

import UIKit
import SpriteKit

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
        }
    }
}

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if let scene = MenuScene.unarchiveFromFile("MenuScene") as? MenuScene {
            // Configure the view.
            let skView = self.view as! SKView
            skView.showsFPS = true
            skView.showsNodeCount = true

            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true

            /* Set the scale mode to scale to fit the window */
            scene.scaleMode = .AspectFill

            skView.presentScene(scene)
        }
    }

But it only shows a grey screen not the scene, is there something else I need to make?


Solution

  • is your MenuScene an sks file? probably not, you just have the swift file as the scene.

    If I understand correctly, the unarchiver takes an sks file and unarchives it, look at the "unarchiveFromFile" method, see the if statement, and the else returns nil.

    you can probably do this:

    if let scene = new MenuScene() {
    

    instead of the unarchive. Otherwise make an sks version of the MenuScene file.