Topic was automatically imported from the old Question2Answer platform.
Asked By
vonflyhighace2
Old Version
Published before Godot 3 was released.
I’m trying to get the parent node of a child node.
Example
parent
child
child
child
I want to get the parent. A script is attached to the last child in the hierarchy. I was using get_parent().get_parent().get_parent(). what would be the best way to goo about it.
Documentation is your friend. You can use absolute path: get_node(“/root/parent”)
Is it possible to do this if the parent is not based on an absolute path. I have many different parent nodes so i can’t use a fixed node path to the parent.
vonflyhighace2 | 2016-06-27 14:10
If the node “parent” is not the first node in the tree (it’s not connected to the root viewport) and your example is general, absolute path won’t work. If you have many parent nodes connected to the root viewport, it should work.
GlaDOSik | 2016-06-29 20:31
But if you know how many levels up the parent is you can also use a relative path: get_node("../../../parent")
You can use “…” to traverse through the ancestors.
If you have a hierarchy like this
world
boat
gun
If you call get_node("../../") from the gun, you will get the world node.
Additionally, you can do in script export(NodePath) var parent_path
and then you can browse and choose required node from the editor itself. Later if you change the hierarchy, you just need to select the path in the editor and don’t require to edit the script.
Does it matter how many nodes are in the hierarchy? If there are a bunch of nodes in the parent will this still work? I have to get the parent during runtime so a fixed path wouldn’t work for my case.
Traverse SceneTree up in Godot is expensive. And Best practices recommends passing reference from parent to child. So this is “true way”
var scene_tree:SceneTree
func _ready() -> void:
scene_tree = get_tree()
scene_tree.connect("node_added", self,"on_node_added")
for i in get_child_count():
var child:Node = get_child(i)
if child.is_in_group("wants_parent_ref"):
child.my_parent = self
func on_node_added(node:Node) -> void:
if !is_a_parent_of(node):
return
if node.is_in_group("wants_parent_ref"):
node.my_parent = self
DECLARE @id INT = 6
;WITH parent AS
(
SELECT id, parentId, 1 AS [level] from tbl WHERE id = @id
UNION ALL
SELECT t.id, t.parentId, [level] + 1 FROM parent
INNER JOIN tbl t ON t.id = parent.parentid
)
SELECT TOP 1 id FROM parent ORDER BY [level] DESC