How to get node from another scene?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Andika Satya Wisnu
:warning: Old Version Published before Godot 3 was released.

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?

:bust_in_silhouette: Reply From: timoschwarzer

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

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.

dejvid_bejlej | 2017-11-26 21:04

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?

BetterRage | 2019-10-09 16:51

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(...))

timoschwarzer | 2019-10-09 16:53

:bust_in_silhouette: Reply From: cardoso

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.

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

exuin | 2021-03-28 15:10