Godot Version
v4.2.1.stable.official [b09f793f5]
Question
In my game, the player can explore and transition between different rooms (scenes) and each room has its own set of enemies inside.
I want to create a simple system where if an enemy is killed in one room, then the player leaves and later returns to the room, the game will remember that this enemy has been killed and will not spawn it.
My current implementation of this was to create an autoload that will store the name of the room and an ID of the killed enemy in a dictionary, and once the player returns to that room, the enemy will check if its ID is registered in that dictionary like so:
Audoload (GlobalSave):
var defeated_enemies := Dictionary()
func insert_defeated_enemy(scene_name: String, id: int) -> void:
if defeated_enemies.has(scene_name):
defeated_enemies[scene_name].append(id)
else:
defeated_enemies[scene_name] = [id]
func check_defeated_enemies(scene_name: String, id: int) -> bool:
if defeated_enemies.has(scene_name):
return defeated_enemies[scene_name].has(id)
return false
Enemy class:
class_name Enemy
@export var id: int
func _ready() -> void:
if GlobalSave.check_defeated_enemies(get_node(GlobalPaths.ROOM).scene_file_path, id):
queue_free()
func _on_enemy_death() -> void:
GlobalSave.insert_defeated_enemy(get_node(GlobalPaths.ROOM).scene_file_path, id)
queue_free()
This works well for the most part, however you may notice that the id
variable is an export, meaning that when I create my rooms, I have to manually assign IDs to every enemy I add and make sure no two enemies in the same room share the same ID.
I had another idea which was to add a script to my room scenes and have it assign IDs to all of the enemies inside itself:
func _ready() -> void:
var set_id := 0
for enemy: Enemy in $Enemies.get_children(): #$Enemies is just a holder node which contains all enemies in the room
enemy.id = set_id
set_id += 1
However this did not work, because for some reason, the _ready
function of the enemies runs before the _ready
function of the room (even though the enemies are grandchildren of the room scene?)
So that’s why I came here. Could anyone help me figure out how to automatically assign IDs to enemies and store them?