How to/is it possible to initiate another instance's function?

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

I’m trying to make a bullet deal damage to an enemy on collision and check if its health is less than 1, and if so, initiate its deathInitiate()function so the enemy dies and is removed in the same frame.
I couldn’t figure out how to do this, though I thought of just bringing that function to the bullet itself and applying it to the enemy (but I really don’t wanna do this and feel like its a last resort)

:bust_in_silhouette: Reply From: magicalogic

In the enemy script add the function to take damage:

func take_damage(damage_amount):
    damage -= damage_amount
    if damage < 1:
        initiate_death()

Declare the initiate death function in the same enemy script:

func initiate_death():
    queue_free()

Then in bullet script, declare bullet damage amount and a hit function:

var damage_amount = 10
func hit(body):
    if body.has_method("take_damage"):
        body.take_damage(damage_amount)

Also make sure to connect body_entered signal to the hit function in _ready() function.

func _ready():
    connect("body_entered", self, "hit")

I have assumed you are using godot 3 since you didn’t specify which version you are using. If you are using godot 4 and have problems converting the code just comment on this answer.

I’m not home yet to try, but is the damage dealt and enemy destroyed in the same frame?

chickencorner | 2022-12-11 05:47

queue_free() will destroy the node when ready. It may be this frame or the next but that’s a very small time difference that can’t even be noticed.
Why is it so important anyway?

magicalogic | 2022-12-11 07:21