Get root node in scene

Godot Version

4.3.stable

Question

If I’ve got a player scene and in it I have a node with a script. In that script I want to acces the Player node but I don’t want to use get_parent() a bunch of time. Is there is a way to acces the Player node directly no matter the scene the Player is in?

You usually use signals to get up the tree

1 Like

You could always have a top-level var in your script:

var Player

func _ready():
    Player = get_parent()

After that, Player has a reference to the parent you can just use; you don’t have to keep refreshing it with get_parent().

yeah but I would like to acces the root node of the file no matter the position of the node with the script

you can use owner then

1 Like

there is no “root node of the file”, there is only one root.
when you instantiate a scene, it is a added to the tree as a bunch of nodes.
any references you want to get have to be obtained within the scene, with either get_node/$, get_parent(), or with a reference to a node added in code.

that said, there are many ways to implement features like these.
you don’t need input as child of the player, it can be its own node and get a reference to player through export.
it can also obtain the player reference through groups.

the only reason to have per-player input would be multiplayer, but at that point I would also have a single input node and control the other players through a different multiplayer-input node, since they need to receive input from the internet and not the main computer.