How exactly do signals work and are they efficient?

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

In the game I am developing, I am trying to understand and decide the best way for certain objects to share information with each other. For example, the player script which handles and calculates player health needs to share its data with the player’s GUI to update the value property of their health bar (TextureProgress).

For the given scenario, would it be better to…

A: On the player script, assign a variable for the GUI script so that the player script can directly modify the GUI by doing “gui.health_bar.value = new_value”

OR

B: Connect a signal from the player script to the gui script so that the player script does not need to assign a permanent variable for the GUI and can instead simply do “emit_signal(“update_health”, new_health)”

Is there a major difference in efficiency between these two methods, or are they essentially the same? This issue is generalizable throughout much of the game so I figured it might be important to know which way is better.

Thank you!

:bust_in_silhouette: Reply From: maxwellc055

For all intensive purposes these should be essentially the same. To my knowledge, signals are reasonably efficient; but more than that, they’re convenient and fun.

The benefit of a signal is it is made to only be called when it is needed.

For example, in option A, the GUI script must be constantly reading the variable to be ready for changes. (Albeit this should have no real performance cost in this case given the insignificance of the size of the data).

Option B, on the other hand, would not require the GUI script to constantly read that data. Instead the data would be updated only when a function is activated in the player script that could change the health of the player (the function connected to the signal).

Another interesting option to consider is a global script, or singleton. These set up data that can be simultaneously accesses by any node’s script. You can read more about that very simple process here.

:bust_in_silhouette: Reply From: wyattb

The signal should be more efficient because your publisher code does not have to pause to update a UI and especially if you have multiple subscribers/listeners.

Using signals has other advantages.

If you make changes to the subscriber, e.g. the GUI. you don’t have to change the game code (the publisher).

Also your code is cleaner overall because game logic is separate from the UI.