+1 vote

I have an "Enemy" scene and a "Bullet" scene, the enemy has "health" and the bullet has "damage", both of these variables are asinged when the coresponding scene is instanced. When a bullet and an enemy colide, I want that exact enemy take damage equal to the damage variable of that exact bullet. However I dont know how to reference a variable inside of an instanced node (at least none of my atempts worked).

my code for instancing bullets:

export (PackedScene) var BulletScene

func _process(delta):
    if Input.is_action_pressed("ui_select") and shot_ready:
        var Bullet = BulletScene.instance()
        Bullet.damage = 10

my code for instancing enemies:

export (PackedScene) var enemy_scene

func _on_Timer_timeout():
  var enemy = enemy_scene.instance()
  enemy.max_health = 20

I would idealy have a script inside the enemy scene that decreases its health equal to the damage of the bullet that hit it, but as I said before I dont know how to get that value. I am still new, so any help will be very apreciated.

Godot version 3.4.2
in Engine by (13 points)

1 Answer

+3 votes

You can have a singleton with a bullet hit event.

# game_events.gd (AutoLoad)

signal bullet_hit_enemy(bullet, enemy)  # Parameters are optional here

In the bullet script, emit the signal when the bullet collides with an enemy.

# bullet.gd

func _on_area_entered(area):
    var parent = area.get_parent()
    if parent.is_in_group("enemies"):
        GameEvents.emit_signal("bullet_hit_enemy", self, parent)

Now you can listen to this signal anywhere in your code.

# enemy.gd

func _ready():
    GameEvents.connect("bullet_hit_enemy", self, "_on_bullet_hit")

func _on_bullet_hit(bullet, enemy):
    if enemy == self:
        health -= bullet.damage
by (62 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 Frequently asked questions and 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 [email protected] with your username.