Error with assigning a health value

Godot Version

4.5

Question

Currently I am trying to declare the health value of a unit in my strategy game. However, when I do I get the error “Invalid assignment of property or key ‘health’ with value of type ‘int’ on a base object of type ‘null instance’.”

I’ve set up the health to be defaulted at 100 through an export variable. However when I try to change it in the Swordsman script, the error pops up.

Help would be appreciated and if you need more details, please let me know.

Swordsman script:


UnitStorage script:

Scene Tree:

1 Like
@onready var Swordsman = $Swordsman

The Swordsman script has no Swordsman node, therefore when it looks for the reference, it fails to find it and returns null.
You cannot access Swordsman.health because Swordsman does not exist here.

You need to access this node from the UnitStorage script, which has HUD, Swordsman and DamageButton.

You should also probably remove that reference from the Swordsman script, as what that would essentially mean is var swordsman = self, and if you want to change the health from within that script it’s enough to do health = 150.

If you want to get references to nodes in the current scene, and have them autocomplete with @onready appended, you can click and drag the node from the tree into the script, hold down CTRL and let go.

2 Likes