Tiptech
Tiptech

Reputation: 177

Use a boolean value from another scene in SpriteKit

I am trying to use a variable from my GameScene.swift file on my GameViewController.swift file to time my interstitial ads appropriately. It's a boolean value that determines if my player is dead or not.

var died = Bool()

That's all I did to create the variable in my GameScene.

When died == true in my GameScene, I want to send that to my GameViewController and then show an interstitial ad. How can I pass a boolean between scenes?

Upvotes: 1

Views: 142

Answers (2)

Alessandro Ornano
Alessandro Ornano

Reputation: 35402

You can follow these steps.

Do this in your GameScene:

protocol PlayerDeadDelegate {
    func didPlayerDeath(player:SKSpriteNode)
}

class GameScene: SKScene {
    var playerDeadDelegate:PlayerDeadDelegate?
    ...
    // during your game flow the player dead and you do:
    playerDeadDelegate.didPlayerDeath(player)
    ...
}

In the GameViewController you do:

class GameViewController: UIViewController,PlayerDeadDelegate {
     override func viewDidLoad() {
        super.viewDidLoad()
        if let scene = GameScene(fileNamed:"GameScene") {
              ...
              scene.playerDeadDelegate = self
        }
     }

     func didPlayerDeath(player:SKSpriteNode) {
         print("GameViewController: the player is dead now!!!")
         // do whatever you want with the property player..
     }
}

Upvotes: 1

Tushar
Tushar

Reputation: 3052

Your GameScene should have a reference object as delegate (e.g conforms to GameSceneDelegate protocol) which is actually pointing to GameViewController object. Then when died becomes true, inform your delegate object (GameViewController object) about this event via a delegate-method and implement that method by conforming to the above protocol in your GameViewController class.

Upvotes: 0

Related Questions