0 votes

I want to know how to make a variable (let's call it count for now) which equals a number (lets say 10) to have 1 subtracted from it every second. So after one second count = 9, then count = 8, then count = 7, etc.

Godot version Godot 4
in Engine by (26 points)

3 Answers

+2 votes
Best answer

Option 1

Use process delta
- The fastest implementation but not entirely precise

#process time
export var count = 10
var delta_time = 0

func _process(delta):
    delta_time += delta

    if delta_time >= 1.0:
        delta_time = 0
        if count > 0:
            count -= 1

Option 2

User timer

  1. Or use a timer
  2. set it to 1 sec
  3. connect to the following script

infinite loop possible stack overflow

func _on_timeout():
    count -= 1
    if count > 0:

Option 3

Use Yield or OS.get_ticks_usec() or OS.get_time()

by (6,262 points)
selected by

Thank you for helping out so much! And giving so many possible answers! I'll be sure to try them all out! Thanks again! :D

+1 vote

Most easily you can use the Timer node, how to use it like this on Godot 4

var count := 10

func _ready():
    var timer: Timer = Timer.new()
    var subtract = func():
        count -= 1
#       if the count value reaches 0
#       then the value will be made 10 agains
        if count == 0:
            count = 10

    timer.connect("timeout", subtract)


by (84 points)
edited by

This looks very nice.

Thank you for your help! It is very much appreciated! :D

+1 vote

I believe simplest way is :

func countdown():
        for x in range(count-1):
              count -= 1

except yield is wait in Godot4

by (7,743 points)

Thanks for your help! I appreciate the syntax change note! :)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.