How to have a signal script be reused by multiple node?

Godot Version

4.5 Stable

Question

Currently I have a unit node that has an attached sprite and button node, this unit node is stored in a scene. I plan to instaniate the unit node in the main scene and I’m worried that connecting the button node through editor signals may not work, so I chose to use a script to connect the signals I’m using. I am wondering if it possible to reuse a script multiple times, because I wasn’t able to find out how.

Yes, you can safely reuse the same script. Each instance of your scene gets its own copy of the script, so connecting signals in _ready() works for every unit:

@onready var btn = $Button


func _ready():
    btn.pressed.connect(_on_pressed)


func _on_pressed():
    print("Pressed:", self)

An alternative you can try look at is the event bus pattern, in this case, signal bus.
Use an autoload that holds shared signals. Each unit emits to the bus instead of directly to other nodes:

# signal_bus.gd (autoload)
signal unit_pressed(unit)
# unit.gd
@onready var btn = $Button


func _ready() -> void:
    btn.pressed.connect(func(): SignalBus.unit_pressed.emit(self))

This keeps everything decoupled and works great when you have lots of units. Also, any other script from other nodes can connect to this same signal without know about the button existence.

1 Like

how would I reuse the same script for each unit

When you attach a script to a scene, every instance of that scene automatically uses that same script.

You don’t need to do anything special to “reuse” it. Just instantiate the scene normally, and each clone already has the script attached and runs its own _ready(), signals, etc.

Hi
Maby Here’s the key point:

Signals are connected to NODES, not scripts
When you connect a signal (either in editor or through code), it attaches to the specific node instance, not to the script itself. Each unit instance gets its own:

Copy of the script

Set of signal connections

Button node with its own pressed signal

1 Like