How to make enemies not all take damage at once

Godot Version



I’m trying to make several instances of an enemy that take damage separately. However, when you attack one enemy, they all take damage. My code is as follows:

func _on_spear_area_3d_2_body_entered(body):
	spearcollision = 1
	hp -= incoming_damage
	if (incoming_damage < hp):
	await get_tree().create_timer(0.01).timeout
	spearcollision = 0

I know that the reason it doesn’t work is that every enemy receives the signal, but I don’t know how to get around this.

You are leaving out some important details. Is _on_spear_area_3d_2_body_entered in the enemy class? Is body the enemy entering into the area that causes damage? I’m going to assume the latter, though the purpose of your code is unclear to me.

If body is your enemy class, then have a function there that accepts damage, and call it:

func _on_spear_area_3d_2_body_entered(body):
	spearcollision = 1
	spearcollision = 0

Implement doDamage(…) in your enemy class, and make hit points a member of your enemy class, so you can do something like this:

func doDamage(nAmount):
    # Reduce hit points
    m_nHitPoints -= nAmount
    if m_nHitPoints <= 0:
        # enemy instance is dead. Notify handlers.

       # Remove the enemy instance from the scene.

It worked! Thank you. Sorry for not being clear enough, I’ll try to be clearer on what me code does in the future.