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()
used_bullet.hide()
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:
sprite.show()
var used_bullet = magazine[bullets - 1]
used_bullet.hide()
bullets -= 1