Connect signal from tilemap-painted scene node to Main UI node

Godot Version

4.2

Question

I’m trying to connect a “clicked” signal defined in a scene I made (Fort.tscn) to a UI element in my main scene. The UI element is a Control node, child of the root Node2D. The Fort node is instantiated by a TileMap painting (Scene Collections), not in code.

Question: How can I connect the clicked signal to the main scene’s UI node upon instantiation?

Structure of Main Scene
World (Node2D)

  • TileMap
  • MainUI (Control)

If I put the following code into the _ready function of MainUI (which I would like to do), then fort_node is assigned <Object#null> and everything throws an error.

I can do this in a seemingly bad-practice way: in the _process function of my UI node, I have the code

var fort_node = get_parent().get_node(TileMap).get_node(Fort) fort_node.clicked.connect(_on_fort_clicked)

And then in the same script I define _on_fort_clicked(): print("FORT WAS CLICKED"). This works fine, but since I’m calling this in the process function, it reassigns fort_node and tries to connect the signal every frame, which seems…very non-optimal.

UPDATE/EDIT: I solved this by putting an await statement in the _ready function. Now the body of the _ready function of MainUI reads:

await get_tree().create_timer(.06).timeout
var fort_node = get_parent().get_node(“TileMap”).get_node(“Fort”)
fort_node.clicked.connect(_on_fort_clicked)`
(The .06 seemed to be the sweet spot.)

New Question: Is this bad practice, to use a simple await statement like this? Are there preferable alternatives?

You may want to use an event bus singleton in this case. Tutorial here The Events bus singleton · GDQuest

_ready() is called from bottom to top of the SceneTree (children before parents) so awaiting may or may not work depending on a lot of factors. You can read how the SceneTree initializes and process the nodes here Node — Godot Engine (stable) documentation in English (in the Scene Tree section) and here Using SceneTree — Godot Engine (stable) documentation in English

1 Like

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