+2 votes

Is there a way to get a node (from the current scene), if not knowing the exact node path?

Scene structure:

-- player
-- item

In the item script I want to access the player node

I tryed using find_node(), but aparently it's not working.
If I use get_tree().get_root().get_node("level").find_node("player") it works,
but if I use get_tree().get_root().find_node("player") it does not.

in Engine by (384 points)

1 Answer

+4 votes
Best answer

If you want to find something on children, set owner to false in the parameters

find_node ( mask, true, false)


Keep in mind that find_node is slow, could be better to add the node to the "player" group and get it by searching groups (or even call_group if it is for something simple).

by (7,894 points)
selected by

Also I'm pretty sure there is a better way to make item and player interact rather than creating globals, hardcoding paths or searching nodes.
Usually, collision detection and signals are a good fit for this, but it depends on your game.

eons, thanks, it works!

Zylann, actually, it's because of using a signal that I needed to find the player.

I want to make the player and the item interact - when the player (body) enters the item (area) - so I use a signal. (And for my logic I need to know the item position in the signal method, which I pass a extra parameter.)

So I created a script for the item, where I connect() it with the player.
And I don't want to have the player path harcoded there.

If you know a better way to organize this, I am open to know :)

If you do this through collision, you can either send the collider to the collided using a function, and this way you won't need to use get_node, find_node or signals at all ^^

Zylann, thanks!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.