Label isn't updating

So I do not know why my label won’t change i am making the base of a clicker game and this is the only script i have. I have narrowed it down to it being an issue with my varible not updating

extends Node2D

var clicks

func _ready() -> void:
	$Counter.text = str(0)

func _process(delta: float) -> void:
	$Counter.text = str(clicks)

func _on_Button_pressed() -> void:
	print("Clicked")
	clicks =+ 1
	print(clicks)
	$Counter.text = str(clicks)

Hi,

I guess it should be clicks += 1 instead of clicks =+ 1, which just assigns the value to 1 each time.

6 Likes

Here’s the solution:

extends Label

var clicks: int = 0

func _ready() -> void:
	$".".text = str(0)

func _process(_delta: float) -> void:
	$".".text = str(clicks)

func _on_Clicker_Button_pressed() -> void:
	print("Clicked")
	clicks += 1
	print(clicks)
	$".".text = str(clicks)

I have the script set to the label node

I would recommend removing the _process-function.

Right now, you set the label to display str(ticks) every frame. It is better to only update the label when the value of ticks changes.

Quick remark about @MrBrokeIt’s code: using $".". is very redundant to access a script’s node variable, as you can just type self., which is much more readable, or just type nothing at all.
Also, as @baba mentioned, the label should be updated only when the clicks counter changes, doing it in process function is pointless here.

By the way, last small improvement about the code: in the ready function, instead of setting the label to “0”, I believe it’s cleaner to set it to the initial clicks value, which will be 0, but, if for some reason the initial value is different, then the ready function will have a correct behaviour.
That could happen, for instance, when loading a save file that already has some clicks in it.

Anyway, here’s what I think is a proper code:

extends Label

var clicks: int = 0

func _ready() -> void:
	text = str(clicks)

func _on_Clicker_Button_pressed() -> void:
	clicks += 1
	text = str(clicks)

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.