What is the Nil value? Is it the same as null?

Godot Version

4.3

Question

What is the Nil?

Code from Learning-GDScript-by-Developing-a-Game-with-Godot-4/chapter07/player.gd at main · PacktPublishing/Learning-GDScript-by-Developing-a-Game-with-Godot-4 · GitHub

extends CharacterBody2D


const MAX_HEALTH: int = 10


@onready var _health_label: Label = $HealthLabel
func _ready():
	update_health_label()


func update_health_label():
	if not is_instance_valid(_health_label):
		return

	_health_label.text = str(health) + "/" + str(MAX_HEALTH)


func add_health_points(difference: int):
	health += difference

Why if remove if not is_instance_valid(_health_label): and change Health in Inspector for example 6 i se error

Invalid assignment of property or key ‘text’ with value of type ‘String’ on a base object of type ‘Nil’.

If is_instance_valid returns false then return is executed.
Return causes us to simply exit the function?

Then godot calls the code again and _health_label is already correct and returns true and this code from if is confused.

1 Like

Which line gives the error?

Nil represents that you’re variable was never initialized (I guess it’s the same as in Lua scripts).

For this case in particular, see if the Scene that you’re running contain $HealthLabel.

Also, if the $HealthLabel is a node from a scene being instantiated inside other scene, you should to pass the whole path to that node from the node that contains your script.
For example, if you have a Scene like:

CharacterBody2D
  Node
    HealthLabel

You will have to pass @onready var _health_label: Label = $‘Node/HealthLabel’
If otherwise, you have:

Node
  HealthLabel
CharacterBody2D

You will have to pass @onready var _health_label: Label = $‘…/Node/HealthLabel’

The two dots use is the same as in the cd command on Linux, it’s used to go one level upper in the hierarchy.

1 Like