Search code examples
iosswiftsprite-kitbooleanskscene

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?


Solution

  • 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..
         }
    }