How to limit a Spawner to x # of mobs and lower that limit when one dies?

Godot Version

4.3

Question

How can I make a mob spawner keep track of the number of children it has instantiated and lower that when one of the children gets queue_free()d from the scene?

Currently, I have a Node2D with a spawner script attached to it and a marker and a timer for children. The spawner script instantiates rats as children of the marker at the markers global_position. The rats can then be killed by the player and queue_free() out on death.

Below is the entire spawner script right now. It basically instantiates a rat every x seconds (based on the timer value) until it reaches 5 and that’s great. However, I want the spawner to continuously try to be at 5, not just spawn 5 rats.

extends Node2D

@export var spawn_limit = 5
var spawned_mobs = 0


func spawn_rat():
	if spawned_mobs < spawn_limit:
		spawned_mobs += 1
		const RAT = preload("res://Scenes/rat_enemy.tscn")
		var new_rat = RAT.instantiate()
		%spawn_point.add_child(new_rat)

func _on_spawn_timer_timeout() -> void:
	spawn_rat()

I’m having difficulty figuring out how to subtract 1 from the spawn_limit when one of the children dies? Or is there some way to count the number of ‘rat_enemy’ children and then use that value to replace the spawned_mobs variable?

I was thinking I could send some sort of signal to the spawner like on_mob_death.emit(), but I don’t know how to connect the signal since they are instantiated after the game begins running.

I also thought of sending the death to a global script and have the global script subtract 1, but there are multiple spawners and don’t know if there is a way to select the specific spawner the mob was from.

Thanks y’all!

The easiest way would be a signal for the enemy.
Create a signal “died” on the enemy and emit it when it dies and change your spawner code to this:

extends Node2D

@export var spawn_limit = 5
var spawned_mobs = 0


func spawn_rat():
	if spawned_mobs < spawn_limit:
		spawned_mobs += 1
		const RAT = preload("res://Scenes/rat_enemy.tscn")
		var new_rat = RAT.instantiate()
		new_rat.died.connect(_on_rat_died) # Here we connect the signal through code
		%spawn_point.add_child(new_rat)

func _on_rat_died():
	spawned_mobs -= 1 # Here we reduce the amount of spawned-mobs because one has died

func _on_spawn_timer_timeout() -> void:
	spawn_rat()
1 Like

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