#Function does not wait until Sprites have loaded, but I use @onready

4 messages · Page 1 of 1 (latest)

slim thistle
#

Heyho!
I have a 2D-Node "Hook" with 3 sprites ("Base", "Chain" and "Head") and a variable "distance".
I want to expand the chain by the amount of "distance" using a setter. Same for the hook-head.

But the scene crashes stating that "chain" and "head" are nil.

extends Node2D

@onready var chain : Sprite2D = get_node("Chain")
@onready var head : Sprite2D = get_node("Head")
@export var distance : int = 0 : set = _set_distance

func _set_distance(value): 
    head.offset.y = value // Crash here, Invalid get index 'offset' on base 'Nil'
    chain.region_rect.size.y = value // Crash here, Invalid get index 'region_rect' on base 'Nil'
    distance = value

I thought @onready would defer all function calls until the annotated nodes have loaded?

#

As a reference, this is what is supposed to happen

cloud drift
#

iirc, onready vars are initialized after export vars, so you're trying to set the export var before the nodes exist in your scene.
You could do a simple null check inside of that function. That's one solution I guess