Get node after instanciation : null instance

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

Hello guys,
from time to time i face the following problem:
Instancing a scene, add it as child and access it in _ready() or another “early” called function.

In the following example:
I instance a “Main_menu” (CanvasLayer) - it has itself “Start” (Button) as child - and add “Main_menu” as child to my Node2D to which the following Script snippet is attached to.
I want to instance Main_menu, add it as child and then connect to the “pressed” signal of the Start button. I do this essentially in the ready() function of Node2D.

onready var Main_menu = load("res://scenes/Main_Menu.tscn").instance()
onready var start_button = $Main_menu/Start

func _ready():
	open_main_menu()

func open_main_menu():
	add_child(Main_menu)	
	start_button.connect("pressed", self, "start_button_pressed")

The following error occurs:

error message: attempt to call function ‘connect’ in base ‘null instance’ on null instance. (referring to the line where start_button.connect is called)

I tried to fix this with yield(), deferred() and other functions since i expect that the Main_menu instance is not ready when i want to connect to its child “Start”. Feel free to give advices and technical info since i am very new to Godot and would like to learn how it works.

Thanks for your help in advance.
Chris

:bust_in_silhouette: Reply From: juppi

Hey Chris,

just change this line…

onready var start_button = $Main_menu/Start

… to this

onready var start_button = Main_menu.get_node("Start")

Thank you very much! (I was already crying about this)
Do you know what’s the technical difference between these commands or is this just a kind of bug?
I faced this problem so often and never solved it. Always worked around.

ErdnussMaus | 2022-03-19 09:34

I think because …

onready var start_button = $Main_menu/Start

… is called before the Main_menu has been added as child.

You can also do this:

onready var start_button;

func open_main_menu():
    add_child(Main_menu)    
    start_button = $Main_menu/Start
    start_button.connect("pressed", self, "start_button_pressed")

juppi | 2022-03-19 12:10