Null instance help on a Label

Godot Version

v4.2.1

Question

This is probably a very basic question, so I’m hoping that if this is not the place, someone can direct me to where this should be.

I have a very simple program in which objects randomly spawn and fall. When they cross the bottom of the screen, they decrease the score by 10.
This works a few times, and then stops and my stack trace tells me “Attempt to call function 'update_score” in base “null instance” on a null instance.

The Node2D that falls has this code excecuting:

if global_position.y > get_viewport_rect().size.y:
		%Score.update_score(-10)
		call_deferred("queue_free")

The score label has this code:

extends Label

var score = 0;

func update_score(points: int):
	score += points
	text = str(score)

I added the call_deferred as I thought it might be an issue with the falling object calling and then disappearing before the function finished, but it doesn’t appear to be the case.

Any idea from these code samples or is it something else going on?

Thanks,

I made a small change and it seems to now work, can someone tell me why the below works but the original does not?

if global_position.y > get_viewport_rect().size.y:
#		%Score.update_score(-10)
		get_node("/root/Game/CanvasLayer/Score").update_score(-10)
		call_deferred("queue_free")```

Attempt to call function 'update_score” in base “null instance” on a null instance

Try to understand what this error means. You want to call a function called update_score but the engine doesn’t know which node you mean. Null instance means that there is no reference to a node, so Godot tries to call a method on basically nothing.

Your second code snippets seems to work because godot know what node you want to call, because you provided an absolute path.
My guess is, that the % property wasn’t set up correctly.

1 Like