How to easily access nodes that are in a different branch of nodes?

Godot Version 4.3 Beta 1

Question

I want to address from the World node (see screenshot) to the Label node, and more specifically to its Text parameter. At the moment the only solution I see is to get all references to all parent nodes, and then from them go down to the child nodes (see code). But it seems too complicated to me.

I also tried writing a direct path (relative to root), i.e.

_Label = GetNode("root/Main/CanvasLayer/Control/Label") as Label

but as expected it didn’t work (probably because of different node creation times).

So, if an alternative way is more optimal?

// DELETE_AFTER_TEST
private Node2D _Grid;
private Node _Main;
private CanvasLayer _CanvasLayer;
private Control _Control;
private Label _Label;
// !DELETE_AFTER_TEST

public override void _Ready()
{
    // DELETE_AFTER_TEST
    _Grid = GetParent() as Node2D;
    _Main = _Grid.GetParent() as Node;
    _CanvasLayer = _Main.GetNode("CanvasLayer") as CanvasLayer;
    _Control = _CanvasLayer.GetNode("Control") as Control;
    _Label = _Control.GetNode("Label") as Label;
    // !DELETE_AFTER_TEST
}

изображение

Oh, I found a way, there was a bug in my code. I just had to add a slash before root:

_Label = GetNode("/root/Main/CanvasLayer/Control/Label") as Label;

with no casting you can use
_Label = GetNode<Label>("/root/Main/CanvasLayer/Control/Label");

1 Like

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