Storing object references as variables

Godot Version



I’m trying to create a bullet counter in my HUD, showing each bullet as a sprite at the bottom of my screen, then hiding each bullet’s sprite as soon as it’s fired.
I’m doing this by creating an array of sprite references, then popping back from the magazine array every time a shot is fired.
I’m then storing each bullet sprite in a variable and trying to .hide() it.
The code looks like this:

extends Node

var magazine = [$CanvasLayer/Magazine_UI/Round1, $CanvasLayer/Magazine_UI/Round2, $CanvasLayer/Magazine_UI/Round3...]

func _on_player_shoot_sig():
	var used_bullet = magazine.pop_back()

It crashes and returns “attempt to call function “Hide” in base “Null Instance” on a Null Instance”.

I’m guessing I’m fundamentally misunderstanding how GDScript works.
Can I store object refs as variables and call functions like in the code above?
If not, how can I achieve my goal?

Array.pop_back() removes and returns the last element in the Array. If the Array is empty it returns null.

You’ll need to keep how many bullets you have and use that to get the bullet in the array.

Something like:

extends Node

var magazine = [$CanvasLayer/Magazine_UI/Round1, $CanvasLayer/Magazine_UI/Round2, $CanvasLayer/Magazine_UI/Round3...]
var bullets = magazine.size()

func _on_player_shoot_sig():
	if bullets <= 0:
		# Magazine empty, reset bullets counter and show all the sprites again
		bullets = magazine.size()
		for sprite in magazine:
	var used_bullet = magazine[bullets - 1]
	bullets -= 1

I tried this but the problem remains the same, each sprite causes the error:
@implicit_new(): Node not found: “%RoundX” (relative to “Node”).

EDIT: the % is because while troubleshooting I tried giving unique names to all the bullets, that’s not the problem with the code.

That’s a different issue that the one before.

I just noticed. You need to set @onready when defining the magazine variable.

@onready var magazine = [...]
1 Like

D’OH, such a simple thing. That’s what happens when you work the night away lol
Thanks for the help, works like a charm now!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.