Can I use an onready variable if instantiating a scene via script?

Even while following tutorials, I like to make (mostly stylistic) changes on how I’d code something in real life. The logic is the same after all.

I initially had this to set the game over score:

extends Control


@onready var score = $Panel/Score

func set_score(new_score: int):
	score.text = "Score: " + str(new_score)


func _on_retry_button_pressed():
	get_tree().reload_current_scene()

But it gives me a null exception, the score variable is always null:

The tutorial’s code works fine:

extends Control


func set_score(new_score: int):
	$Panel/Score.text = "Score: " + str(new_score)


func _on_retry_button_pressed():
	get_tree().reload_current_scene()

So why is my onready variable always null? Is _ready not called for script instantiated variables?

1 Like

we had something similar with when we were instantiating bullets.

as far as im aware @onready variables are created before the _ready is called on anything.
but their values can only be set once whatever they are referencing have a presence in the scene tree.

and since in the game.gd script, we are instancing the game over screen, then using the set score then adding to scene.

so to use @onready to reference a scene and use its children, then we have to add it to the scene first so @onready can assign that variable since its now entered the scene tree.

so to get your onready working, ensure these two lines in the game.gd script, have the child being added to the scene first

4 Likes

Due to the similarity with bullets, I was surprised it didn’t work out of the box. Thanks for the explanation!

1 Like

Finally caught up with the Adding Path Enemy To The Spawner lecture which also explains this. I’ll try to be more patient :sweat_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms