Communication between scenes

Godot Version

4.3

Question

Hi,
I’m pretty new and do not know most of the handy solutions so my problem might be trivial to most.

In my game I have two scenes which the player can connect. I do so with some code and buttons (draw a line).

BUT I do not know how I can tell the scenes who they are connected to (there might be several scenes of the same type). I need them to communicate to change values etc. Signals alone don’t solve the problem (I think).

I’m sure there is an easy solution but I just don’t know how to do it.
Thx for any help.

It all depends on the hierarchy and ease-of-communication.
If the parent node has a script, it can define its children via variables and then access their methods and variables.

For example:

# inside root node
%Player.do_something()

The player has little control over knowing who its parent node is despite having access to get_parent() which is very prone to errors.
An elegant way to solve it is for the parent node to give itself as a parameter to the player

# root node
%Player.setup_something(self)
# player node
var root
func setup_something(root_node) -> void:
    root = root_node

Godot’s truest flexibility comes in form of signals and groups.
If you add an object to the group, anything can call the specific objects of the group or call all group members to do something

# inside enemy
func _ready():
	add_to_group("enemies")
# some other script
var all_enemies = get_tree().get_nodes_in_group("enemies")

Right now I believe signals are unbeatable if used in combination with autoloads

# inside autoload (using Connect.gd as example)
signal enemy_defeated(enemy_name)
# inside root
func _ready() -> void:
    Connect.enemy_defeated.connect(func(name): print(name + " has been defeated!"))
OR
func _ready() -> void:
    Connect.enemy_defeated.connect(handle_enemy_defeat)
func handle_enemy_defeat(enemy_name: String) -> void:
    print(enemy_name+ " has been defeated!")
    killcount += 1
# inside enemy
var name = "Grunt Enemy"
func on_death() -> void:
    Connect.enemy_defeated.emit(name)

Just do what is most convenient for you.

1 Like

Thank you for your answers. I found a work around for my problem in the mean time but you gave me some good ideas.

The problem is simple, it is just that I lack the experience and knowledge. It is a long way…

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.