iosswiftuiviewcontrollerskscene

How To Present a SKScene from a UIViewController


I am creating this game in SpriteKit. At first launch, the GameViewController presents another ViewController called the MenuViewController linked with a storyboard. And in the MenuViewController there is a play button that will present a SKScene called the GameScene.

I figured out how to present the MenuViewController from the GameViewController, but I can't find a way to present the GameScene when the play button is tapped. In my code, when the button is tapped, nothing actually happens.

GameViewController:

import UIKit
import SpriteKit

class GameViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {

        let storyBoard: UIStoryboard = UIStoryboard(name: "MenuViewController", bundle: nil)
        let vc = storyBoard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
        self.present(vc, animated: true, completion: nil)

    }

} 

And in the MenuViewController:

import UIKit
import SpriteKit

class MenuViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func playButtonTapped(_ sender: Any) {

         if let view = self.view as! SKView? {
            let scene = GameScene(size: view.bounds.size)
            scene.scaleMode = .aspectFill 
            view.presentScene(scene)
            view.ignoresSiblingOrder = true
            view.showsFPS = false
            view.showsNodeCount = false
            view.showsPhysics = false

         }
    }

}

Also, I got this warning printed into the console:

SKView: ignoreRenderSyncInLayoutSubviews is NO. Call _renderSynchronouslyForTime without handler

I don't know if this is related...

I did set the view of the MenuViewController's storyboard to be equal SKView. I can't find any way to make the GameScene appear. Nothing happens.

Thanks!


Solution

  • I think I might have found a solution-I didn't present the GameScene directly from the MenuViewController, but instead, when the playButton is pressed I transitioned to the GameViewController and then presented the GameScene from there.

    I don't know why it doesn't work in the MenuViewController, but this method works.