0 votes

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.

in Engine by (77 points)

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

2 Answers

+2 votes

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()
by (3,233 points)

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

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
+1 vote

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
by (37 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.