How do you make a counter?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By dezekeerjoran
:warning: Old Version Published before Godot 3 was released.

How do you make a Label, if you press a button it adds one to the number on the label?

:bust_in_silhouette: Reply From: ingo_nikot

1st create a label

add a script to your label:

func _ready():
  set_process_input(true)#this will activate input handeling

func _input(event): # will get called on every input event
  #now we check if a random button got pressed:
  if event.is_pressed() and event.type == InputEvent.KEY and not event.is_echo():
    var val=int(self.get_text()) #get current value and convert  to int for math
    self.set_text(str(val+1))#add one and convert back to string, set label text

“not event.is_echo()” will prevent that holding the button for a few seconds will still only counted once

thank you ^^

dezekeerjoran | 2016-12-24 00:02

This will increment the counter if a key is pressed, not if a button is pressed.

Calinou | 2016-12-24 11:17

yeah i now. i have figure it self out ,how to do it with a button.thanks.

dezekeerjoran | 2016-12-24 11:40

sorry i misstranslated key for button, for your case its a bit diffrent:

possible scene structure:
root_node
\my_btn
\my_lbl

then add script to the root_node. from here you got two possible ways:

A: via code (i prefer this way):

func _ready():
  my_btn.connect("pressed",self,"on_my_func_name_pressed")

func on_my_func_name_pressed():
  #code to increment label, thats the easy part anyway

B: via ide:
-click on my_btn
-click on the node tab
-choose the signal-
-click connect
-click connect in the dialog window that poped up

if you dont change the defult settings a method will be created. in this method you can do the increment stuff.

sorry for the initial confusion :frowning:

ingo_nikot | 2016-12-24 23:45

i already now. but still thanks.

dezekeerjoran | 2016-12-26 13:45

:bust_in_silhouette: Reply From: YeOldeDM

This code should be a little cleaner and easier to work with. Maybe over-complicated for a simple system like in the question, but more often than not these things evolve into more complex monsters :slight_smile:

extends Label

var count = 0 setget _set_count

func _set_count(what):
	if what==count:return
	what = count
	set_text(str(count))

func increment():
	set('count', count+1)

Now, for whatever input method you want to use, have it call the increment() method.
In the case of a button press, simply connect your button’s “pressed” signal to the label, and have the signal call the method “increment”