Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrecognized selector sent to instance with Timer

Im making a game with spritekit and would like to check for some updates in variables each second (instead of using the update method which checks too often). I created a scheduledTimer that has a selector of the function that I want to run, but it gives me the error: Unrecognized selector sent to instance.

I understand that the function probably needs the correct sender, but what is it? Thank you

var timer = Timer.scheduledTimer(timeInterval: 1, 
                                       target: self,
                                     selector: #selector(GameScene.updateEachSecond), 
                                     userInfo: nil,
                                      repeats: true)

func updateEachSecond() {
   print("1 second has passed")
}
like image 253
Rudi Thiel Avatar asked Mar 30 '17 20:03

Rudi Thiel


1 Answers

You need to declare your timer

var timer = Timer()

as a property of your GameScene

and move your timer initialization to didMove(to: or any other method that runs after your scene has finished loading.

override func didMove(to view: SKView) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateEachSecond), userInfo: nil, repeats: true)
}

Another option as suggested in comments is to check in your update method if the second changed:

var timeInterval: TimeInterval = 0
var time = 0

override func update(_ currentTime: TimeInterval) {
    if timeInterval < currentTime.rounded(.down) {
        time += 1
        timeInterval = currentTime
        updateEachSecond()
    }
}

func updateEachSecond() {
    print("Time:", time, terminator: "s\n")
}
like image 135
Leo Dabus Avatar answered Sep 25 '22 10:09

Leo Dabus