I have two scripts, first is AsteroidSpawner script that literally spawns object named Asteroid, and second is HUD that control all UI related stuffs.

There are some labels in UI, so I used onready to get those nodes:

extends CanvasLayer

class_name HUD

onready var asteroids_label = $Control/RightContainer/AsteroidCountLabel

func set_asteroids_label(value: float):
	asteroids_label.text = "Asteroids: " + str(value)
	pass

However, when I try to access HUD script, with set_asteroid_label, it gives me null error:

var spawned_asteroids: Array = []
onready var hud: HUD = get_tree().get_root().find_node("HUD", true, false)

func _ready():
	spawn_asteroids()

func spawn_asteroids():
    ... spawn asteroid ...

    spawned_asteroids.push_back(asteroid_instance)

    hud.set_asteroids_label(spawned_asteroids.size()) # UPDATE HUD

Invalid set index 'text' (on base: 'Nil') with value of type 'String'

I guess that HUD is not ready, but AsteroidSpawner script try to accessing it, wasn't it? Then how should I wait until HUD is loaded?

Hi modernator,

I know this may seem weird, but can you just try setting your hud variable in the _ready() function directly using get_node() giving it the full path and see if that works?

Something like this:

get_node("/root/path/to/HUD")

Docs on get_node: https://docs.godotengine.org/en/3.1/classes/class_node.html#class-node-method-get-node

Thanks, but I fixed by using code like this:

yield(hud, "ready")

There was a signal exists when invokes when script is loaded.

3 years later