How do I update the score?

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

I am writing my first own simple game. I am trying to display the score with an richtextlabel. I update the score in another script.

Every time _process() runs in the score script, richtextlabel-text is set to be score.

But my output is super weird when I print the score, it is 1 and 0 and 1 and 0 and so on. I don’t get this. The score is fully working, I have tried up to 50, but every other frame it is set to 0.

This is surely a stupid question, but that is how we learn… I hope…
Any help or explanations are appreciated.

This is from the script which adds to the score. The score script is global.
Score-counter-script

Here text is set to the score.
Code

And this is the weird output.
Output

:bust_in_silhouette: Reply From: Wakatta

Seen it many times with new programmers and must come down harshly on you so you won’t develop a hard to break bad habit.

  • Avoid assigning variables of other classes directly when possible

Like in the problem above it’s possible the score var is being manipulated elsewhere since your code is pretty straight forward

  • Use functions and avoid _process loop func for everything

for e.g

extends RichTextLabel

var score := 0

func update_score(new_score : int):
    score += new_score
    text = str(score)
    print(score)

Using global vars everywhere makes it hard for you to debug your code, makes it harder to implement new changes, makes version control look messy and limits you from new languages

Thank you for your answer.
I have got one question though. Can I access that function from another script? If the script is global right? I think I tried that but the score still went crazy.

Masemiliano | 2022-10-14 04:59

Ok nvm now it works but the text gets incredibly small when it gets updated from another script.

Masemiliano | 2022-10-14 05:09

Yes

Global.update_score(1)

Wakatta | 2022-10-14 05:23

Most likely because the score var is being changed somewhere else.

In the script editor you can do a search of all files for “score” to see all cases where it is changed

Wakatta | 2022-10-14 05:26

But why would the text on screen get small? That’s weird

Masemiliano | 2022-10-14 05:27

I just realized that auto load doesn’t just mean that the variables get global, it also litterally means that the script gets autoloaded. I think I can figure it out from there.
Thank you for the help, I really appreciate it.

Masemiliano | 2022-10-14 05:49