How to get the main node of a scene instance

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

How do i go about getting the main node so like the parent of all the nodes of a scene through one of its children in an instance of that scene? So like, i have a hitbox inside my character scene and i wish to get the damage variable from the KinematicBody2D node which is the main node of that scene, but i don’t want to use stuff like get_parent().get_parent().damage as the hitbox is an instance of the hitbox scene which i use in other characters as well but not in the same exact position so for other characters i would need to do a different amount of get_parent(). And because the scene will be instanced i can’t go about the get_tree().get_root().get_node(“KinematicBody2D”) way. Is there perhaps a different way of going about this?

:bust_in_silhouette: Reply From: automatrio

You can use get_tree().get_root().get_node(), but it has to be inside the _ready() function.

The first thing your node will do when it’s instanced is execute whatever is in the _ready() function; and it’ll already be a part of the tree. Just one little advice: don’t forget to set it as a child of some node, i.e., to call add_child(my_new_node), or else you’ll get an error telling you that node wasn’t in the tree.

Now if I misunderstood you, do let me know.

In the end I found a different way of going about it but this seems much more optimal and much less of a mess, I’m guessing this will work so thanks a bunch !

Jashooter | 2021-02-06 19:51