Why is my label returning as null? It’s properly referenced from the scene. I can’t solve this.
Here is the code:
extends Node2D
var cur_dialogue := 0
@onready var label = $NinePatchRect/Label
@export var dialogue_lines = [
"Default Line",
]
func _ready():
visible = false
print(dialogue_lines[cur_dialogue])
func dialogue():
if not is_visible():
visible = true
if cur_dialogue < dialogue_lines.size():
if label: # Check if 'label' is not null
label.text = dialogue_lines[cur_dialogue]
else:
print("Label node not found or is null.")
print(cur_dialogue)
cur_dialogue += 1
else:
print("End of dialogue reached.")
if Input.is_action_just_pressed("Advance Dialogue"):
visible = false
cur_dialogue = 0
and the Hierarchy:
Any help is greatly appreciated, I have been trying to solve this for a while.
I tried out this code in a new project (Godot 4.2.2 also), and added a call to dialogue() at the end of _ready(), and it is properly setting the non-null label’s text… Can’t seem to reproduce this.
Can you try this 3-node hierarchy in a new project? Where is dialogue() being called from?
Okay, I was able to reproduce this, by calling dialogue() in a different node’s _ready() method, which was run prior to node’s _ready() method above (before the @onready label was set).
I think that doesn’t matter, and it would be bad code styling for a var to come after _ready(). It could be easier for the person to delete the line and ctrl drag it again.
when you get null for a node in a variable with @onready and you call it via _ready()
you should be aware that the @onready’s var may not be added to child yet when this node is _ready. so what you can do is
to add
What does the stack trace look like? If you set a breakpoint at the line with the “label is null” print statement, what do you see? Is there a _ready() call in it somewhere? That would indicate things aren’t all fully initialized.
it will always null because he tries to spawn just script, not the scene. because it’s a script object, it will never run @onready variable line
hence it will never find label node because DialogueBox scene is never spawned