Getting the root node

Description

I want to ask how I could get the root node from a script attached to a node. This sounds idiotic but the script attached to it will be an instance of a new scene. I’m a beginner-intermediate and I’d love to hear your help!

Godot Version

4.3.stable

get_tree().root

If script extends NOT from Node extended class, you need to make your own singleton that extends Node and then address root from it
DataGlobal.get_tree().root

I was trying to get a node from the root with get_tree().root.get_node(“Player”) but it didn’t succeed with this message:

Invalid access to property or key ‘root’ on a base object of type ‘null instance’.

The node must be a part of the scene tree to use get_tree(), maybe try this code after using add_child(node)?

It should be possible to get the root node anywhere, even outside of a Node extended class, via Engine.get_main_loop().root.

1 Like

Solution

I realized that the mistake I made was that I forgot to add @onready :man_facepalming:! I hope no one makes this mistake again!

I want to state that @ratrogue was indeed correct and it is an alternative way to get the root node! I suggest writing @onready var A_Variable = get_tree().root.get_node(“RootNameNode”).get_node("TheTargetNode")