How to subtract from a value repeatedly over a certain amount of time.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By NewbieGodotUser

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.

:bust_in_silhouette: Reply From: Wakatta

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()

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

NewbieGodotUser | 2022-09-15 18:26

:bust_in_silhouette: Reply From: sarapan_malam

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 =
    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)


This looks very nice.

Wakatta | 2022-09-14 23:00

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

NewbieGodotUser | 2022-09-15 18:25

:bust_in_silhouette: Reply From: Inces

I believe simplest way is :

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

except yield is wait in Godot4

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

NewbieGodotUser | 2022-09-15 18:24