I can't get the enemy health decrease more than once

Hi, today is my second day learning to code in Grodot, so I think I’m probably not doing this in the best way.

I set a hitbox for my player and my enemy, I have a bullet script and I use a set_health function to set the enemy’s health like this:

const Enemy = preload(“res://scenes/enemy.tscn”)
var enemy = Enemy.instantiate()

func _on_body_entered(body: Node2D) → void:
set_taking_damage(current_damage) # current_damage is a var that my gun script send to the bullet, so I can use the same bullet script for others guns

func set_taking_damage(damage):
enemy.set_health(damage)

and in the enemy script I have this

func set_health(damage):
if health <= 100:
health = health - damage
print(‘health inside if’, health)
else:
print(‘else’)
queue_free()

The problem is that every time I shoot, the enemy’s health stays at 70, since the bullet’s damage was set at 30, but the health doesn’t go down from that as it should, it always resets to 100 when another bullet hits the enemy.

It’s because in the bullet script you are not using the enemy that are being hit, but a new instance of a enemy that is not in the current scene tree.

You can remove this part:

const Enemy = preload(“res://scenes/enemy.tscn”)
var enemy = Enemy.instantiate()

And change the _on_body_entered and set_taking_damage to something like:

func _on_body_entered(body: Node2D) -> void:
    if body is Enemy:
        set_taking_damage(body, current_damage)

func set_taking_damage(enemy: Enemy, damage: int) -> void:
    enemy.set_health(damage)

So with this, you will apply the damage to the enemy that is coming from the _on_body_entered method.

It worked! Thank you! The only change I need to make is to use the enemy’s group:

func _on_body_entered(body: Node2D) → void:
if body.is_in_group(‘enemy’):
set_taking_damage(body, current_damage)

I tried using

if body is Enemy

but I got this error:
Parse Error: Could not find type “Enemy” in current scope.

Just wondering, am I missing something for this Enemy type to work?

Thanks again for your help!

Haha yeah, the if body is Enemy part would work only if the the Enemy script had a class_name on it, but the way u did it’s cool too :slight_smile:

Don’t forget to close the thread :wink:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.