Search code examples
iosswifttimernstimer

How to set up a timer and display it on a game scene with Swift


I am trying to set up a timer that counts from 60 seconds to 0 and display the count on my game scene. However, I keep running into issues when I do the following: In my GameScene.swift file I created the following:

 var gameTimer = 60
 var timer = Timer()
 @IBOutlet var timerLabel: UILabel!

under the GameScene class, then under the ViewDidLoad I did:

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameViewController.startTimer), userInfo: nil, repeats: true)

where startTimer was a function with the following content:

    @objc func startTimer()  {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameViewController.updateTimer), userInfo: nil, repeats: true)
}

and updateTimer is another function to update the timer:

    @objc func updateTimer(){
    gameTimer -= 1
    timerLabel.text = String(gameTimer)

}

But the game keeps crashing when I launch it. What am I doing wrong here? Any help is appreciated.

For those of you who asked about the error message: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

And it is pointing to this line of code:

        timerLabel.text = String(gameTimer)

Solution

  • If the line timerLabel.text = String(gameTimer) causes this crash, it means that the timerLabel variable holds nil at that point. Make sure that your @IBOutlet is connected with the label in the storyboards.

    Also, unrelated to your problem right now, instead of

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameViewController.startTimer), userInfo: nil, repeats: true)
    

    call

    startTimer()
    

    in the viewDidLoad directly.

    The timer created in startTimer() is responsible for updating the number every second, you should not start it again and again