Array created with @onready is <null>

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


I have a Node2D with this script:

@onready var recipe_items : Array = []
@onready var recipe_quantities : Array = []

func add_item(item, quantity):
	print("in 'add_item' recipe")
	print("recipe_items: ", recipe_items)

and the line recipe_items.append(item) returns the error Invalid Call. Nonexistent function 'append' in base 'Nil'.

and yes, the print("recipe_items: ", recipe_items) returns recipe_items: <null>

But I create the Array with the @onready, doesn’t that mean that when the Node2D is instantiated, the array is created “first”?

I do that in another script:

@onready var recipe_scene = preload("res://recipe.tscn")
-- stuff --
var recipe_instance = recipe_scene.instantiate()

for item in added_items:
	print("item in for loop: ", item)
	print("item[0] in for loop: ", item[0])
	recipe_instance.add_item(item[0], item[1])

None of the above print() returns null. But this line jumps to the func add_item(item, quantity) at the top, which then gives the error that the array recipe_items is null.

Shouldn’t var recipe_instance = recipe_scene.instantiate()start the line @onready var recipe_items : Array = [] hence, NOT be null?

I’m confused.

Thank you!

:bust_in_silhouette: Reply From: Robbas

After recipe_scene.instantiate() I added the instance to the tree as child (or sibling): add_child(new_recipe) (or add_child(recipe_instance), in my case it’s new_recipe because I do that in another function)

So the conclusion I made from this is that @onready, and probably the the func _ready() doesn’t run until the instance is added to a tree.

Someone correct me if I’m wrong!