+3 votes

I want to call function from another scene. How to do this?
how to get node from another scene? can i useget_node()to get node from other scene?

in Engine by (32 points)

2 Answers

+15 votes
Best answer

You can get a node from another scene like this:

var node = get_node("/root/scene_main_node/node_wanted"),
or var node = get_tree().get_root().get_node("scene_main_node/node_wanted"),
or
var tree_root = get_tree().get_root() var node = tree_root.get_child( tree_root.get_child_count()-1 ).get_node("node_wanted")
(you get the last child because you might have autoload scripts loaded)

To call a function is as normally:
node.function_name()

So in these cases you need to know the path to a node in another node. The best is to try to avoid this, as if the path changes, then the code breaks.
Also it becomes harder to test scenes in isolation, as the reference to the other scene node will be null.

So it might not be a bad idea idea to organize code in other ways. Like have a level manager (script) that access the nodes you need, and if the path of the nodes change you always node in which file to update the paths. And you can use signals to let the level manager know something happened in the nodes.


Edit: timoschwarzer answers's "<path>" more accurate, as in my case it is assumed that the node you wanted was a child of another's scene main node.

by (370 points)
selected by

This answer is not very good. You really shouldn't use the getchildcount()-1 method unless you're 100% sure that the other scene is the last child of root and always will be.

+1 vote

You can get any node in your Scene tree by using get_node("/root/<path>").

by (698 points)

Hi, I know it's and old post and it's a stupid question but I can't get it to work no matter what, that's the scene path:

res://Scenes/Player/Player.tscn

Could you show me how to write it? I need the main node of that scene.

I have the same question, i need to reference the rootnode of another scene(in my case player) but i dont know how i can. do you have the answer now?

The scene file path is completely irrelevant to the resulting node path. It depends on where you add your scene to your node tree. (e.g. where you do add_child(...))

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.