0 votes

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

in Projects by (52 points)

2 Answers

+1 vote

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

by (289 points)

thank you ^^

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

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

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

possible scene structure:

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

A: via code (i prefer this way):

func _ready():

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

i already now. but still thanks.

0 votes

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

extends Label

var count = 0 setget _set_count

func _set_count(what):
    if what==count:return
    what = 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"

by (1,318 points)
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 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 webmaster@godotengine.org with your username.