+1 vote

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():
    build_map()

func build_map():
    print(section.get_name())

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

Godot version 3.2
in Engine by (359 points)

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.

3 Answers

+1 vote

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.

by (1,462 points)

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?

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

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.

0 votes

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

https://github.com/godotengine/godot/issues/33620

by (14 points)
0 votes

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.

by (567 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.