This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

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
in Engine by (56 points)

1 Answer

+1 vote
Best answer

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 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)

by (519 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.