how to make a enemy counter

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By thoma

hi, i want to make something can count the number of enemy left whit a label node but i don’t now how to code it ?
Thank do helping me.

if all your enemies are a child of some node - get_child_count(). it’s better to add them all to a group though i think and then get the number of nodes in the enemy group

Squatnet | 2019-04-22 17:54

:bust_in_silhouette: Reply From: Magso

Like @Squatnet said, you can put all your enemies in a group and get the amount of them by using get_nodes_in_group()

var enemies
var enemyCount

func _ready():
    enemies = get_tree().get_nodes_in_group("enemyGroup")
    enemyCount = enemies.size()

so i did it this way, but now when i kill the first enemy, the number stays the same; once i kill the second enemy, then it starts to go down… any idea?

Example: Tanks A, B, C. I destroy tank A, enemyCount is still 3. I destroy tank B, then enemyCount is two

tmit30 | 2020-08-13 00:58

That would only happen if you’re doing something like this

enemies = get_tree().get_nodes_in_group("enemyGroup")
enemyCount = enemies.size()

When you only need to do this

enemyCount -= 1

Magso | 2020-08-13 11:23

:bust_in_silhouette: Reply From: Dr. Numerus

I think the best option is indeed the group one.

But in case you do not want to do it with a group, you could do it with global variables.
Just add a Global singleton script via project settings → AutoLoad and store a variable for the enemies there.
Then every enemy can manipulate this global variable with their own script:

func _ready():
       Global.enemy_counter += 1
       # other actions

func _killed():
       Global.enemy_counter -= 1
       # other actions

The label can also access it via this method:

func _process(delta):
       self.text = Global.enemy_counter