Can't get child with $

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

In my scene for ‘item’ I have this structure:

- Control
-- Button
-- VBoxContainer
--- HBoxContainer
--- HBoxContainer
--- HBoxContainer

The GDScript on Control I have

@onready var button = $Button

but returns null. I do a similar thing in another script without problem:

@onready var container = $VBoxContainer
@onready var item_name = $VBoxContainer/Name
@onready var item_price = $VBoxContainer/Price
@onready var item_unit = $VBoxContainer/Unit

elsewhere I instantiate the ‘item’ with

var item_instance = item_scene.instantiate().

Is there any known issues with referencing children with $ on instantiated scenes?

Double check that you have this script attached to Control.
Does the $Button auto-complete? If not then the parser isn’t seeing the node Button.
(You can also check this in the _ready() function by simply print(button))
If it does then there is another reason variable button is null and it is not related to the code you are showing.
It might help to show the code where the error is occurring.

I am curious about the last line

var item_instance = item_scene.instantiate()  

You do not instantiate from an instance variable (one that is created by $).
For example in your code sample, you would get an error doing:

var item_name = item_name.instantiate().

I am sure you already realize this but it isn’t 100% clear to me in your post.

LeslieS | 2023-01-23 05:20

Sorry for late response.

The script is attached to Control.
The $Button auto-complete.

I also have

@onready var item_scene = preload("res://item.tscn")

and use that var for

var item_instance = item_scene.instantiate()

My guess is that I try to create the Button-reference before the item is instantiated properly.

Must I add some kind of delay or something?

Robbas | 2023-01-28 09:54

Can you show where the error is?
onready will define the variable once the node is attached to the tree.
It is possible to fire code before that happens so maybe that is what is happening.
In that script attached to control add a print to the func _ready() to make sure you have the button node.

func _ready(): 
    print(button, " my button")   

If that prints null then you aren’t connecting to the node for some reason.
If the error happens before xxx my button is printed then you know for sure you are trying to access the node prematurely.

LeslieS | 2023-01-29 02:20