Format for connecting a signal from a node instanced as a scene

Godot Version

Godot Version 4.4.1

Question

Hi, I have a question about what I should do when trying to connect signals via code. Let’s say I have Node A in my main scene. Then Node B in another scene. I load Node B in and have a signal in its script that I want to emit to a function in A.

Is using get_node(“../NodeA”) the thing to do here in order to begin connecting the signal? Then use signal.connect(node_a.function).

signal example

var node_a = get_node("../NodeA")

example.connect(node_a.function)

I’m curious because I want to keep things loosely coupled, though it seems when instancing an node I need to use get_node to connect the signal. I wanted to confirm if this is the correct way to do things.

I would use a signal bus instead.

Generally speaking you should avoid parent paths i.e. ../ this also tightly couples your code to a specific scene tree path and only to one node.

If you load node b then you can give it values and assign connections after instantiation, rather than within the node b to the outside.

var new_node_b = NodeB.instantiate()
new_node_b.example.connect(node_a.function)

But this if you have any specific questions that might prove more useful than talking theoretically.

Connection should be made from the instantiating code that’s hierarchically above both nodes, not from the instantiated node.

Thanks for your answer. I see what you mean. I took an example from GDQuest’s best practices with node signals. Let’s say I have two trees.

- Main
- Level
- Player
- Health
- UILayer
- User Interface
- Health Bar

When the player’s health changes a signal will be emitted to the health bar in the user interface to show the change visually.

To connect the signal, would I maybe do it in a script in the “Main” node or maybe make another node that’s above the Level and UILayer nodes with the purpose of connecting signals?

I would put the UILayer inside the player, setting health would be a function that calls down into the UI

Thanks. In case the UI is in another scene, I found an example this site suggests down in step 2. Thanks everyone for your help.