Richard Murff Richard Murff - 1 year ago 72
Swift Question

Use SKSpriteNode as button to transition from GameScene to UITabBarController

I have a

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

I have an
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 = {
if name == "exit" {

In GameViewController.swift:

var currentGame: GameScene!

override func 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
currentGame = scene

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

This is the line giving the error:


Answer Source

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.