Neel Sarwal Neel Sarwal - 1 year ago 54
Swift Question

Restartarting GameViewController/GameScene

Once my game is complete, I am running

self.performSegueWithIdentifier("goToGameOver", sender: nil)
in my GameViewController, which holds my GameScene through

override func viewDidLoad()

let scene = GameScene(size: view.bounds.size)
let skView = view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
skView.ignoresSiblingOrder = true
scene.scaleMode = .ResizeFill
scene.size = skView.bounds.size

Then, in my GameOverViewController when the user clicks my playAgainButton it runs
self.dismissViewControllerAnimated(true, completion: nil)

But then it goes back to my GameViewController/GameScene which doesn't reload and is in the same state which it was left in... How can I "reinitialize" or re-present the GameScene through my ViewController's SKView?

This sort of problem is also in my store, when a user clicks a side arrow it moves "modally" to a different ViewController and they buy my ingame currency, but when they click my back arrow and I run
self.dismissViewControllerAnimated(true, completion: nil)
The elements such as my UILabel linked with an IBOutlet, is not updating the new amount of in-game currency... If I'm not wrong, then it's because the viewcontroller/scene isn't reloading. How would I fix both of these issues?

Answer Source

You can save user state via Core Data or using NSUserDefaults for lightweight data. When GameScene is initialized, GameScene can load state from the local store. This would also mean that you would need to write to the local store when when deallocating GameScene. In addition, this would also solve the ingame currency issue. Simply update your Core Data model when the user has added credits.

An alternative to this would be using the delegate pattern. Define a protocol which GameScene conforms to within GameOverViewController. GameScene would not be deallocated when presenting GameOverViewController because GameOverViewController would have a reference to GameScene. Therefore, that instance of GameScene would have a reference held by GameOverViewController (to add credits, update labels, ect.). For an example of the delegate pattern, check out my answer here

I would recommend going with the first approach as using persistence will save user state between launches.