If I may suggest a simpler solution: You don’t need the main scene to delete your enemies.
In your enemy.gd
script:
@export var health: int = 20:
set(value):
health = value
if health <= 0:
die()
func die():
//do stuff
queue_free()

To answer your spawning questions, you could do something like this in your main.gd
script:
# Width of the spawn area on the x-axis
@export var width: float = 1.0
#Length of the spawn area (y-axis in 2D, z-axis in 3D)
@export var length: float = 1.0
# Number of starting enemies
@export var num_enemies: int = 5
# In the editor, drag and drop the enemy scene into this.
@export var enemy_scene: PackedScene
var rng = RandomNumberGenerator.new()
func _ready() -> void:
propogate(num_enemies, enemy_scene)
func propogate(number: int, scene: PackedScene):
for i in number:
spawn(scene)
func spawn(packed_scene: PackedScene) -> void:
var scene = packed_scene.instantiate()
scene.position.x = rng.randf_range(-width, width)
scene.position.z = rng.randf_range(-length, length)
add_child(scene)
I added code for randomly placing items because I thought it might help. It assumes a square level. Your code will have to be more complex otherwise.
Now, let’s assume you want to track how much xp the player got for each enemy killed. That would be a great use for a signal. You could add to your player.gd
:
var xp: int = 0
func connect_enemy_death(enemy: Node) -> void:
enemy.death.connect(_on_enemy_killed)
func _on_enemy_killed(experience: int) -> void:
xp += experience
You would update your enemy.gd
with a signal:
signal death(experience: int)
@export var health: int = 20:
set(value):
health = value
if health <= 0:
die()
@export var xp_value: int = 50
func die():
death.emit(xp_value)
queue_free()
Then you would connect them in your main when you spawn the enemies:
func spawn(packed_scene: PackedScene) -> void:
var scene = packed_scene.instantiate()
scene.position.x = rng.randf_range(-width, width)
scene.position.z = rng.randf_range(-length, length)
add_child(scene)
player.connect_enemy_death(scene)
Hope that helps! I tried to keep the code generic so you could spawn in other enemies, breakables, NPCs, etc.