Why doesn't onready var work?

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

Every time I try to use the onready var to reference a node, it always loads everything before the onready var. Making the variable null. I don’t want to have to keep referencing global nodes in the _ready() function if I don’t have to.

onready var section = $level 

func _ready():
func build_map():

Attempt to call function ‘get_name’ in base ‘null instance’ on a null instance.

I have this same issue. I had a working game, and all of a sudden the node variables declared as ‘onready’ stopped working and gave ‘null’ results as if they didn’t exist in the scene. I tried everything to get it to work, and found a work-around which is to declare the variables in the _ready function but that is just messy and doesn’t seem right.

frasando | 2021-05-07 15:13

1 Like
:bust_in_silhouette: Reply From: AlexTheRegent

onready is always executed before _ready() function. $ is just shortcut to get_node function. If you are adding level node in build_map function, then onready will return null. You can add level node in Editor so it always exists and modify your build_map to reuse already existing node.

So, I don’t understand. You say onready is always executed before _ready(), than my question is: why does adding my level node to my build_map function return null? Especially, if onready DOES in-fact execute first? Shouldn’t my print work then?

Dumuz | 2021-01-08 23:31

Is there level node in editor? Or do you create it dynamically?

AlexTheRegent | 2021-01-09 14:47

It’s a 2D node that is already in the editor. It has another 2D node as it’s first child.
I’ve noticed that when I print(section.get_child(0)) it actually prints the objects type and ID just fine, but when I print(section.get_name()) it claims I’m calling get_name() on a null object. I don’t get it.

Dumuz | 2021-01-10 04:33

:bust_in_silhouette: Reply From: Alejandro

It happens to me when I use onready in an inherited class.
And it seems that this is how it should work:

:bust_in_silhouette: Reply From: Merlin1846

It doesn’t work because like AlexTheRegent said onready is always executed before _ready(). This means that the reference to the node is made before the node exists so the reference becomes null.

Also, this is Godot 3.2 not 2.0 use section.name instead the old system is slowly being phased out which might also explain why it’s not working. Also, you might want to update your engine version you’re x.2.x versions behind.