Referencing the root node

Godot Version

4.6.3

Question

I have a singleton..

extends Node

var scene: Node
var grid: Node

And a script on my default scene.

extends Node

func _ready() -> void:
	game.scene = get_tree().current_scene
	game.grid = Node.new()
	game.grid.name = "grid"
	game.scene.add_child(game.grid)

But when I run and look into remote tab I see this.

Why does it show game and then create a new node as its sibling? I just want to reference the root node easily from my singleton without it creating a new node.

Any script/scene added as a global will be created before the main scene, so if you added your main scene’s script then you will have a duplicate. This is never advised.

If you only want to reference the main scene then you can use get_tree().current_scene, you do not need a global. The sample you posted is essentially double-work the engine already does for you.

Is there a way to reference it from my singleton or should I just use my singleton init for pregame setup?

extends Node

var scene: Node
var grid: Node

func _init():
	scene = Node.new()
	scene.name = "_"
	grid = Node.new()
	grid.name = "grid"
	scene.add_child(grid)

And have a dummy scene loaded as default with nothing in it.

I’d avoid _init if you can, it’s run at a state where basically nothing is ready, including the node itself. _ready is almost always better.

I’m not sure what you mean, get_tree().current_scene is what you would use if you want a reference to the main scene, the only prerequisite is the calling node must be in the scene tree too, so _init won’t work but _ready will.

Overall these questions sound very strange, maybe this is an XY problem? Could you explain the big picture what you are trying to do? What led you to this code?

I’m trying to create a singleton where I can easily reference various stuff such as root node. How would I reference the root node, “game”, without it creating duplicates?

Ok, then yeah get_tree().current_scene is pretty much it. There is no possible way to reference the main scene without it existing, and it won’t exist on _init.

You won’t need a global/singleton to reference the main scene, but for anything else you can create a separate script to take up the global/singleton position.

ok thx