How do I pass varibles between two instanced nodes?

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

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
        add_child(Bullet)

my code for instancing enemies:

export (PackedScene) var enemy_scene

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

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.

:bust_in_silhouette: Reply From: samildeli

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