Projectiles don't reset along with scene after player death

Godot Version

godot-4

Question

I am having issues with "Attempt to call function ‘add_child’ in base ‘previously freed’ on a null instance."

My player character has a weapon that fires projectiles. When the game loads, the projectiles fire just fine. But when the player dies and the scene resets, firing projectiles causes this error.

extends Sprite2D

@onready var marker2d:Marker2D = $Marker2D
const slimeball = preload(“res://Assests/Scenes/slime_ball.tscn”)

func _ready() → void:
pass # Replace with function body

func _process(delta: float) → void:
look_at(get_global_mouse_position())

func shoot() → void:
var new_ball = slimeball.instantiate()
new_ball.position = marker2d.global_position
new_ball.target_position = (get_global_mouse_position() - marker2d.global_position).normalized()
GlobalData.world.add_child(new_ball)

I believe that I have to remove the new_ball from the tree when the scene resets but I could be wrong, and I am unsure how one would even accomplish that exactly.

It means that your object assigned to GlobalData.world variable is freed. So it is not a valid object anymore. Check your logic where you assign, free, and create your object assigned to GlobalData.world.

Also please use preformatted text when sharing code for readibility.