Get root node from any node.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Newby

When spawning in things like bullets and enemies i usually just use get_parent().get_parent()... till i reach the root node. I have used get_owner() on somebof my node but i also have some nodes instanced in when the game starts and since they werent part of the scene tree from the start get_owner() doesnt work. Is there a sure fire method to get the root node no matter where the child node is and whether it was instanced or not.

:bust_in_silhouette: Reply From: Taburetk

Try get_tree().root.get_child(0).

:bust_in_silhouette: Reply From: Sween123

Just use get_node()
You can pass a relative path, or the path from the root.
For example: get_node(/root/World)

:bust_in_silhouette: Reply From: avencherus

There are a couple of approaches off the top of my head:

extends Node2D # Your child class.

func get_local_scene_root(p_node : Node) -> Node:

	while(p_node and not p_node.filename):
		p_node = p_node.get_parent()
		
	return p_node as Node


func _ready() -> void:

	printt("Viewport", get_viewport(), get_tree().root) # Game's viewport.
	printt("Current Scene", get_tree().current_scene) # Active scene root.
	printt("Local Scene", get_local_scene_root(self)) # The nearest TSCN root.
1 Like

This was a great help thank you so much for the various options!

Try :
owner.add_child(yourChild)
It’s works fine for me.