+1 vote

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 "Mainmenu" (CanvasLayer) - it has itself "Start" (Button) as child - and add "Mainmenu" 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

Godot version v3.4.2
in Engine by (34 points)

1 Answer

0 votes
Best answer

Hey Chris,

just change this line...

onready var start_button = $Main_menu/Start

... to this

onready var start_button = Main_menu.get_node("Start")
by (939 points)
selected by

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.

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")
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 Frequently asked questions and 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 [email protected] with your username.