Using signals to update a Label whenever a scene-less global class' attribute changes

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

I have a label that I want to use to display the amount of happiness in the player’s tribe. I’m storing the happiness value as an int attribute in a global class/script called “Resources”.

I’m trying to use signals to update the Label’s text whenever Resources.happiness is modified, but I can’t figure it out.

How can I get the label to update it’s text whenever happiness is modified?

I have looked at tutorials and such for this, but I can’t seem to find anything that explains how to connect an attribute without using the 2d-editor. I don’t think I can use the 2d-editor if the script isn’t connected to a scene. I don’t want to arbitrarily connect the script to a scene just to do this.

resource_label class:

extends Panel

func _ready():
   get_node("happiness_amount").connect("happiness", self, "updateHappiness")

func updateHappiness():
   get_node("happiness_amount").text = str(Resources.getHappiness())

Resource class:

extends Node

var happiness = 25

func setHappiness(value):
   happiness = value
   emit_signal("happiness", str(value))

func getHappiness():
   return happiness
:bust_in_silhouette: Reply From: fpicoral

You did not created the signal. You have to add somewhere in the global script signal happiness but I would recommend doing this in a different way.

Here is what I would do:

1 - Change the Resources.gd global script to:

extends Node

var happiness_label
var happiness = 25

func setHappiness(value):
   happiness_label.text = value

func getHappiness():
   return happiness_label.text

2 - Change the resource_label script to:

extends Panel

func _ready():
  Resources.happiness_label = self

To avoid creating a script just to set the global variable happiness_label, you could add the same code to the root node of the scene where the happiness label is but change self to $Path/to/happiness/label/node

If for some reason you want to keep the signal, you would need to create the signal using signal happiness and connect it to the label from the global script. To do that, you can do the same thing as the other way (create a variable to the label and set it to self in the ready function)