Reputation: 537
In the LevelsScene
class I have the code below for selecting a level. The level
is simply a string value.
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if button1.containsPoint(location){
let gameScene = GameScene(size: self.size, level:"Level1")
self.view?.presentScene(gameScene)
} else if button2.containsPoint(location){
let gameScene = GameScene(size: self.size, level:"Level2")
self.view?.presentScene(gameScene)
} else if button3.containsPoint(location){
let gameScene = GameScene(size: self.size, level:"Level3")
self.view?.presentScene(gameScene)
}
}
}
In the GameOverScene
class I would like to pass the level string value to the following code:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let gameScene = GameScene(size: self.size, level:currentLevel) // where current level has been set to one of the levels
self.view?.presentScene(gameScene)
}
The GameScene
knows the currentLevel
but how can I let GameOverScene
know this value without creating an instance of the gameScene
?
Upvotes: 1
Views: 54
Reputation: 1289
You need to set a global string variable on your view controller that represents your GameOverScene. What you will need to do is set the value of this variable when you segue to that screen.
1.) You will need to name the segue (by clicking on it in the storyboard) with an identifier, in this example, "GameOverSegue".
2.) Add a prepareforsegue: method that checks the segue identifier and then sets the level on the view controller for GameOver:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
//check to make sure it is the game over segue being called
if (segue.identifier == "GameOverSegue") {
//set the gameOverVC variable as an instance of the GameOverViewController
if let gameOverVC: GameOverViewController = segue.destinationViewController as? GameOverViewController {
//set the variable on that vc to be the value of the currentLevel string
gameOverVC.level = currentLevel
}
}
}
3.) Wherever you want to programmatically call a segue, you use this code:
self.performSegueWithIdentifier("GameOverSegue", sender: self)
Upvotes: 2