onready var null when using scene.instance()

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

I created a project where I instantiate some domino pieces, position them on the screen and set the appropriate texture.

I added two pieces to the scene manually and instantiated dynamically all the combination to see if they work.

Everything worked fine until I replaced my local var sprite: Sprite = $Sprite with a onready var sprite: Sprite = $Sprite

Not event initializing it in the func _ready() worked.

The two pieces I added manually worked regardless, but the dynamic ones return null for the sprite when using load(“res://Piece.tscn”).instance()

Here’s the project: Domino.zip - Google Drive

:bust_in_silhouette: Reply From: njamster

You’re calling set_piece before you call add_child, i.e. before the node’s _ready-function is called and it’s onready-vars are initialised, so le_sprite indeed isnull. Simply reverse the order of both calls and your problem should be fixed:

add_child(piece)
piece.set_piece(n1, n2)