Score system with a label

Godot Version

Godot 4.3

Question

Hello!

So I tried to make a points variable in a Global autoloaded script and then set the text on a Label to the number of points in my Game (Node2D) script by accessing the Label as a unique name (%) but wasn’t really able to do it as the label remained on 0 even though print(Global.points) proved that they were counting up.

I don’t really remember how I coded it (set_text() or Label.text = str(Global.points) I believe) as I deleted that part of the code but I would like to know how to make a score label properly update each point.

This should be fairly straight forward.

You do indeed just update the text on your ScoreLabel with an attached script something like:

extends Label

var score = 0

func _ready():
    update_score_text()

func update_score_text():
    text = "Score: " + str(score)

func increment_score(value):
    score += value
    update_score_text()

Now to have your score in your Global I would usually update the global from this script. Something like:

func update_score_text():
    text = "Score: " + str(score)
    Global.current_score = score

However you might want to update scores from the Global. In this case I would emit a signal called something like ‘score_changed’ from the global. The score label would then listen for this signal and update the label text whenever the global score changes.

Either way your suggestion looks perfectly fine to set the score, but when the points change you need to call it again to update it.:

Label.text = str(Global.points)

However, I would not call your Label ‘Label’, call it ScoreLabel or PointsLabel.

There are many ways to do this. My preference would be to have a SignalManager (some call it a SignalBus) with a signal called something like ‘points_scored(value)’ where value is an int so you can score 1 point or 2 points etc from anywhere in your other scenes by emitting that signal. That signal would be picked up by the label, which updates the score on the UI and the score in the Global.

Hope that helps in some way.

2 Likes