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")
}
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With