how to put a variable in a LABEL, and always keep updating the variable, GDSCRIPT?

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

I put a variable to stay in a LABEL, but when I update this variable this LABEL does not update.

extends CanvasLayer
export var point = 0

func _ready():
 $Label.text = str (point)

Would I need to change the STR to something else?

:bust_in_silhouette: Reply From: aXu_AP

When you set some property or variable, it gets set to value at that point of time. If you want the value to be updated, you need to update it regularly. While Godot doesn’t support such binding out of the box, it’s not hard to make. Put this code into your label:

extends Label

var _target_object
var _target_property

# Use this method to set text
func bind_text(target_object, target_property):
	_target_object = target_object
	_target_property = target_property

func _process(_delta: float) -> void:
	text = str(_target_object.get(_target_property))

Put this instead of your current text setting:

$Label.bind_text(self, "point")

The text should now update every frame.

This could be solved using a Setget, it’s best if you don’t use process

lukifah | 2023-01-08 09:01

Yeah, using setter is more performant option. So if you have a lot of these and the data doesn’t change very frequently, it’s better to use approach from the other answer.

However, in a lot games, the trackable values might change frequently and there wouldn’t be hundreds of labels tracking them, the performance difference likely isn’t going to be noticeable.

Another situation where you’d want to take self updating approach is if you want to track built-in properties which you can’t write your own setter.

In the end it depends on your application and also how you want to organize your code. For example, you might not want to add ui code in player character script. You can still solve this with setter by relaying information via signals - but that adds extra boilerplate code for each property you might want to track.

aXu_AP | 2023-01-08 10:00

:bust_in_silhouette: Reply From: Pomelo

What you want to do is update the text property of the label, when the var point changes value. This is very easy to do with setters and getters (I recommend you read on them since they are super useful). Lets use a setter on the var point, which triggers stuff when it changes value. First you do this:

var point = 0 setget set_point

where setget is a keyword and set_point is just the name of the setter function you will define later, like this:

func set_point(value) -> void:

And you are done! just remember that setters only trigger when another script modifies the value of point, and if you are modifying it in this same script just use self.point = new_value, to trigger the setter