Reputation:
I'm new to Swift, so sorry if this seems like an obvious question.
I'm trying to write a game in Swift, and I have designed a label and a play button in the storyboard.
I've added references to these objects in the GameViewController.swift file as seen here:
// MARK: Objects
@IBOutlet var gameLabel: UILabel!
@IBOutlet var playButton: UIImageView!
// MARK: Actions
@IBAction func playButtonTapped(sender: UITapGestureRecognizer) {
GameScene().gameStart()
}
This belongs to the GameViewController class: class GameViewController: UIViewController
.
However, the main game itself takes place in GameScene.swift. This involves me having to hide the label and image as soon as the game starts. I'm unsure how to set the properties for these objects to hide, since if I did the following in GameScene.swift:
GameViewController().playButton.hidden = true
...the game crashes with a fatal error. The error says: fatal error: unexpectedly found nil while unwrapping an Optional value.
Does anyone have a suggestion for this problem? Any help is much appreciated. Sorry if the information was difficult to understand.
Cheers.
Upvotes: 0
Views: 339
Reputation: 2835
You are creating a new instance of 'GameViewController(), but you want you want use your already existent one. If you only want to create one
GameViewController`, which is probably the case, you could use a static instance variable.
In GameViewController
, put:
static var instance: GameViewController!
In it's viewDidLoad()
, put:
GameViewController.instance = self
Finally, in your GameScene
, switch GameViewController()
with GameViewController.instance
.
Upvotes: 1