Aneesh Poddutur
Aneesh Poddutur

Reputation: 29

How to Transition from One Scene to Another in GameViewController using Timer?

override func viewDidLoad() {
        super.viewDidLoad()
        
        //create timer to transition from title screen to menu screen
        let titleTimer = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(GameViewController.transition), userInfo: nil, repeats: false)
        
        //load title screen -----------------------------------------------------------------------
        if let view = self.view as! SKView? {
            // Load the SKScene from 'TitleScreen.sks'
            if let titleScene = SKScene(fileNamed: "TitleScreen.sks") {
                // Set the scale mode to scale to fit the window
                titleScene.scaleMode = .aspectFill
                
                // Present the scene
                view.presentScene(titleScene)
            
            }

        //transition to menu -----------------------------------------------------------------------
        if let newScene = SKScene(fileNamed: "Menu.sks") {
            // Set the scale mode to scale to fit the window
            newScene.scaleMode = .aspectFill
            
            let sceneTransition = SKTransition.fade(withDuration: 3)
        
            @objc func transition() {
                view.presentScene(newScene, transition: sceneTransition)
            }
        }
            
        view.ignoresSiblingOrder = true
            
        view.showsFPS = true
        view.showsNodeCount = true
            
        }
        
    }

I'm looking to transition from the title screen to the menu after 1.5 seconds using a Timer (which needs a selector). The @objc func transition() isn't being allowed to be created due to the @objc, does the function need to be located somewhere else?

Upvotes: 0

Views: 45

Answers (1)

Josh Homann
Josh Homann

Reputation: 16327

Your function is not on you object (its inside ViewDidLoad). In any case you no longer need the selector or function in Swift. There is now a Timer initializer that takes a closure.

Example:

import PlaygroundSupport

let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
  print("Hello in one second")
}

PlaygroundPage.current.needsIndefiniteExecution = true

Upvotes: 0

Related Questions