How to make the scene change when all the enemies are killed?

Godot 4.3

I’ve been looking, and i can’t find anything to help me with this, does anyone know how to change scenes when all enemies in the current scene die?

CODE:

extends Node2D
var enemy_list = [$"chicken", $"chicken3", $"chicken8", $gateopener, $"chicken2", 	$"chicken4", 	$"chicken5", $"chicken6"]

func _process(_delta):
	if enemy_list.queue_free():
		get_tree().change_scene_to_file("res://scenes/game 	screens/barn.tscn")

queue_free() is a callable function that freed or remove any object from the scene. So you need to do this in another way like this:

if enemy_list == null:

or if it does not works then print it: print(enemy_list) in process and kill all enemies and then tell me its output at the last.

1 Like

It kept reading “<Object#null>” over and over again, even when I killed them

queue_free() doesn’t exist on enemy_list because it is an Array of enemies, further more queue_free() does not work as a condition, it merely deletes the node.

You need to go through each element in your list (a for loop), connect to a signal when the each enemy is removed from the game (.tree_exiting.connect()) and count up a new variable until it reaches the same number as the array has items.

extends Node2D
var enemy_list: Array[Node2D] = [$"chicken", $"chicken3", $"chicken8", $gateopener, $"chicken2", 	$"chicken4", 	$"chicken5", $"chicken6"]
var enemies_died: int = 0

func _ready() -> void:
	# connect to each enemy's death
	for enemy in enemy_list:
		enemy.tree_exiting.connect(_on_enemy_perish)

func _on_enemy_perish() -> void:
	enemies_died += 1
	if enemies_died >= enemy_list.size():
		get_tree().change_scene_to_file("res://scenes/game 	screens/barn.tscn")
1 Like

It gave me an error saying “Invalid get index ‘tree_exiting’ (on base: ‘null instance’)”

One of your node paths is invalid. Do all of the chickens and gateopener exist as children of this node?

yes they are

It would seem one of them is not, or is deleted upon _ready, next time you get that error check your stack trace for local variables, you could see enemy is null and maybe you can look through the enemy_list for null values. You could also print(enemy_list) to look for null values, which based on this post sounds like all of them are null, probably not children of this node.

Maybe share a screenshot of your scene tree?

because this is a big level, i could only show the top
image

Seems like the chickens have more after chicken as denoted by chickenp...