Search code examples
iosswiftsprite-kitskscene

How to detect the current scene in SpriteKit project


In my SpriteKit app I've 3 different scenes and I want to set a specific settings for each scene. I mean I want set visible an AdBanner in MainPage and SomeInfoScene but not in GameScene. How can I do this? This is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.view as! SKView? {

        let mainPage = SKScene(fileNamed: "MainPage")!
        mainPage.name = "MainPage"

        let someInfoPage = SKScene(fileNamed: "SomeInfoScene")!
        someInfoPage.name = "SomeInfoScene"

        let gameScene = SKScene(fileNamed: "GameScene")!
        gameScene.name = "GameScene"

        view.presentScene(mainPage)

        if let currentScene = view.scene {

            if currentScene.name == mainPage.name {

                print("MainPage")
                adBannerView.isHidden = false
            }
            if currentScene.name == someInfoPage.name {

                print("SomeInfoScene")
                adBannerView.isHidden = false
            }
            if currentScene.name == gameScene.name {

                print("GameScene")
                adBannerView.isHidden = true
            }
        }
     }
  }

Solution

  • This is tracked by scene property of the SKView class. For instance:

    if let view = self.view as? SKView {
        if let currentScene = view.scene {
            print("Current scene is: \(currentScene)")
        else {
            print("Current scene is nil")
        }
    }
    

    By the way, your first line really should read:

    if let view = self.view as? SKView { ...
    

    That's the standard/idiomatic way to try a downcast in an if statement.


    Update. You also need to set the name property if you are planning to use that in your game code (in the *.sks file or directly inside your code). For instance:

    let scene = SKScene(fileNamed: "MainPage")!
    scene.name = "MainPage"
    view.presentScene(scene)