get_node for a node in another scene: What am I doing wrong?

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

I have so far scoured the internet and have failed to find a solution to this problem, so I was hoping that someone might know.
I think it’s a problem with the path. It keeps returning null.
In World1:
—player ← Where the script is

In Mainmenu:
—play ← What I’m trying to reference


onready var m = get_node("/Mainmenu/Mainmenu/Camera2D/play")

func _ready():

If anyone knows, please say.

:bust_in_silhouette: Reply From: GreasyMcBeef

If I’m reading your trees correctly, it seems like you included an extra “Mainmenu” in your get_node call’s path.

:bust_in_silhouette: Reply From: Bean_of_all_Beans

It looks like you have two scenes: World1 and Mainmenu. If only one of those is active in the Scene Tree, the other won’t be accessible through the method you are using. I’m unsure how you go about the scene transitions (if you are transitioning between them), but if you call get_tree().change_scene() and pass it the World1 Packed Scene (*.tscn, *.scn files), then the current scene, Mainmenu will be unloaded and removed from the Scene Tree, being replaced with World1. This would be why get_node("/Mainmenu/Mainmenu/Camera2D/play") returns null – the node named Mainmenu doesn’t exist.

One way to pass the play node from Mainmenu to World1 is to use a global singleton – an autoload script that is always accessible during runtime.

You would need to create a new script and call it whatever you would like; I will use “global” for simplicity. Then, add the script as an autoload.

If you don’t know how to add a singleton, see below:
Click “Project” in the top-left, then “Project Settings…”. In the pop-up, find the tab at the top labeled “Autoload”, finally clicking the folder button; navigate to the script file, then click the “Add” button at the far-right. Do note, Godot will most likely replace any underscores with spaces and capitalize all the words.
In the autoload script, make a variable called player. This is where you will transfer the node play from Mainmenu to World1.
Skip here if you already know how to add a singleton.

In the script for the player node in World1, change:

onready var m = get_node("/Mainmenu/Mainmenu/Camera2D/play")


onready var m = Globals.player

(Note: Globals is just the name I am using; you can use whatever name you set for your autoload.)

(I am looking at this after writing it and realizing it might be a tad bit confusing. I hope this is easy enough for you to understand, and hopefully it helps.)

Thank you so much! I knew I was missing something obvious.

dubCode | 2021-02-13 20:45