1
\$\begingroup\$

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 setasteroidlabel, 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?

\$\endgroup\$
  • \$\begingroup\$ What does your node tree look like? What scripts are attached to what nodes? \$\endgroup\$ – rcorre Nov 10 at 3:28
1
\$\begingroup\$

Use yield can wait until it's ready:

func _ready():
    yield(hud, "ready")
    hud.set_asteroids_label(spawned_asteroids.size()) # Works
\$\endgroup\$
0
\$\begingroup\$

Invalid set index 'text' (on base: 'Nil') with value of type 'String' indicates that the issue is with $Control/RightContainer/AsteroidCountLabel, not et_tree().get_root().find_node("HUD", true, false). Make sure that you actually have the correct path to AsteroidCountLabel within the HUD.

One easy way to do this is by selecting the node in the editor and pressing Ctrl+C -- this will copy the relative node path to your clipboard, so you can paste it into the script.

You could also export a var of type NodePath from your HUD and set it to the path of the label in the editor.

\$\endgroup\$
  • \$\begingroup\$ That was correct path. It actually works if I wait until AsteroidCountLabel is not null. \$\endgroup\$ – modernator Nov 9 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.