Once my SpriteKit game has ended, I would like to go back to my UIKit MenuViewController
. From what I've learned so far, using protocol/delegate is the best(?) option, but I haven't been able to get that to work. I know that the protocol would probably go above the class declaration for GameViewController
, and look something like:
protocol GameViewControllerDelegate {
var gameOver: Bool?
}
But I need help accessing that from GameScene
AND getting it to dismiss GameViewController
. Below are the bones of the app, in case that helps.
MenuViewController
class MenuViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func goToGame(_ sender: UIButton) {
performSegue(withIdentifier: "toGameSegue", sender: sender.currentTitle)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationVC = segue.destination as? GameViewController {
if let item = sender as? String {
destinationVC.numberOfPlayers = item
}
}
}
}
GameViewController
class GameViewController: UIViewController {
var numberOfPlayers: String?
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
if let scene = SKScene(fileNamed: "GameScene") {
scene.scaleMode = .aspectFill
scene.userData = NSMutableDictionary()
scene.userData?.setObject(numberOfPlayers!, forKey: "numberOfPlayers" as NSCopying)
view.presentScene(scene)
}
}
}
...
GameScene
class GameScene: SKScene {
var howManyPlayers: String?
override func didMove(to view: SKView) {
if let numPlayers = self.userData?.value(forKey: "numberOfPlayers") {
howManyPlayers = numPlayers as? String
}
print(howManyPlayers!)
}
...
This SpriteKit game has a MenuViewController, a GameViewController, and a GameScene. When you press a button from MenuViewController, data is sent via segue to GameViewController. Before GameViewController presents GameScene it stores the data in scene's userData variable so that GameScene can access it. In this example, it's the number of players.