How can I make a function execute every second in swift?

后端 未结 7 1758
离开以前
离开以前 2020-11-29 01:59

I want to add a score to the top of my scene in the game I am working on. The score is going to based on how long you last, and will increase every second. Thanks for the he

7条回答
  •  [愿得一人]
    2020-11-29 03:01

    You can use one like this:

    var timer = NSTimer()
    
    override func viewDidLoad() {
        scheduledTimerWithTimeInterval()
    }
    
    func scheduledTimerWithTimeInterval(){
        // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateCounting"), userInfo: nil, repeats: true)
    }
    
    func updateCounting(){
        NSLog("counting..")
    }
    

    Swift 3:

    var timer = Timer()
    
    override func viewDidLoad() {               // Use for the app's interface
        scheduledTimerWithTimeInterval()
    }
    
    override func didMove(to view: SKView) {    // As part of a game
        scheduledTimerWithTimeInterval()
    }
    
    func scheduledTimerWithTimeInterval(){
        // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true)
    }
    
    @objc func updateCounting(){
        NSLog("counting..")
    }
    

提交回复
热议问题