Godot Version
Godot version 4.5
Question
I am trying to figure out how best to connect signals.
To test different methods I have made a very small project to later implement the best practice in larger projects.
My small example uses an export var in a “health_bar” UI element, in which I drag the “player” node.
It works, but I am not sure if this is the way to go.
Player:
class_name Player extends Node2D
signal health_changed( new_health : int )
var health : int = 100
var speed_x : float = 600
var speed_y : float = 500
func _ready() -> void:
$Area2D.connect( "area_entered", hit_something )
func _process( delta : float ) -> void:
var direction : Vector2 = Input.get_vector( "left", "right", "up", "down" )
position.x += direction.x * speed_x * delta
position.y += direction.y * speed_y * delta
func hit_something( other : Area2D ) -> void:
print( "hit something" )
health -= 10
health_changed.emit( health )
HealthBar:
extends VBoxContainer
@onready var progress_bar : ProgressBar = %ProgressBar
@onready var label : Label = %Label
@export var node_to_listen_to : Node
func _ready() -> void:
if node_to_listen_to:
if node_to_listen_to is Player:
node_to_listen_to.health_changed.connect( update_stats )
update_stats( node_to_listen_to.health ) # Refresh UI now
func update_stats( value : int ) -> void:
%ProgressBar.value = value
%Label.text = str( value )
This is very basic, but I thought it would be fine for UI.
However maybe for larger projects, and objects spawning mid-game, this might not work.
If you see any part which could be refactored you can of coarse let me know.
But my main concern is the right way to go when it comes to linking signals.
Other possibilities I have come across are:
-Using get_tree().get_root().find_child( “Player” ) to search for and link to a node
-Have a level manager script that links nodes
-Using an events bus singleton
So what is the best practice concerning linking signals?
