Richard Murff Richard Murff - 3 months ago 18
Swift Question

Use SKSpriteNode as button to transition from GameScene to UITabBarController

I have a

UITabBarController
that has two items, the first one being a calendar which is just a
UIWebView
. The second item brings in a SpriteKit game scene and hides the tab bar (The game needs to be full screen).

I have an
SKSpriteNode
image that when tapped, I'd like the view to change back to the calendar view (the first tab bar item). I've searched for a way to do this and have tried various suggestions I've found here on StackOverflow, but nothing is working. The app crashes with the error


"Unexpectedly found nil while unwrapping an optional"


I understand what that error means, just not why I'm getting it. Here is the relevant code (part of which I got from here while trying to figure this out):

In GameScene.swift:

weak var viewController: GameViewController!

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch:UITouch = touches.first! as UITouch
let positionInScene = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(positionInScene)

if let name = touchedNode.name {
if name == "exit" {
self.viewController.gameOver()
self.removeFromParent()
self.view?.presentScene(nil)
}
}
}


In GameViewController.swift:

var currentGame: GameScene!

override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.tabBar.hidden = true
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false

skView.ignoresSiblingOrder = true

scene.scaleMode = .AspectFill

scene.viewController = self
skView.presentScene(scene)
currentGame = scene
}
}

func gameOver() {
performSegueWithIdentifier("backToMain", sender: nil)
}


This is the line giving the error:

self.viewController.gameOver()

Answer

Your code is correct; I think the likely problem is that you are presenting more than one scene without transferring the value of viewController. To track this problem down, use the Find navigator (Cmd+3) to search for presentScene then ensure each call is after you have transferred the value of the viewController property across to the new scene.