Why the get_child function returns Nil even if the node has children?

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

Based on the Design the GUI tutorial and the Control the game’s UI with code Tutorial, I tried to implement those tutorials in my project. In the GUI script, when I tried to assign int MAXHP to a TextureProgress node (which on the code is the variable bar called as onready var bar = $HBoxContainer/Bars/Bar/Gauge) in the following code:

func _on_HUD_start_instanced(MAXHP):
    bar.max_value = MAXHP
    bar.value = bar.max_value

It returned the error Invalid set index ‘max_value’ (on base: Nil) with value of type ‘int’.
Why is it returning Nil, even if the Gauge node is a child of GUI?

what event did you connect to _on_HUD_start_instanced?

volzhs | 2018-06-08 03:51

I’ve connected with an emit_signal("start_instanced", MAXHP) in the HUD script. The HUD is a CanvasLayer and the parent of Interface (Control node). The Interface is the parent of an instanced GUI scene, so the problem should be on the GUI scene. I’ve called print(MAXHP) in the first line of _on_HUD_start_instanced and it is the correct int value (which is 6).

andrebariani | 2018-06-08 13:07

:bust_in_silhouette: Reply From: volzhs

I think you emit_signal too early before parent node is ready.

onready var bar = $HBoxContainer/Bars/Bar/Gauge is executed just before _ready
so if you emit signal to early, bar is actually null

I guess it can be fixed by call_defered("emit_signal", "start_instanced", MAXHP)
or… handle like below.

onready var bar = $HBoxContainer/Bars/Bar/Gauge
var max_hp = 0

func _ready():
    update_bar()

func _on_HUD_start_instanced(MAXHP):
    max_hp = MAXHP
    update_bar()

func update_bar():
    if bar == null:
        return
    bar.max_value = max_hp
    bar.value = bar.max_value

The call_deffered function is not available for CanvasLayer nodes but the if bar == null worked! I’ll pay more attention about emiting signals when the _ready functions begins. Thanks for the answer!

andrebariani | 2018-06-09 20:54