I used the instantiate function to spawn in a enemy, but when the enemy reaches 0 health it deletes every instance of the enemy, how would you go about delete only a singular instance of a scene.

  • Toxe replied to this.

    janieldoohick123

    enemy.queue_free()

    But this sounds more like a logic problem in your code. Are all enemies sharing the same health value? Or do you accidentally send a "kill yourself" signal to all of them instead of only one?

    You should show some relevant code.

    in the parent node there is this code:
    `var enemy_scene = preload("res://enemy.tscn")

    #there is a timer set to five seconds
    func _on_timer_timeout():
    var enemy = enemy_scene.instantiate()
    enemy.position = Vector3(-5, 254, -269)
    add_child(enemy)`

    in the player script there is this code:

    `func _physics_process(delta):

    if Input.is_action_pressed("click") and ray_cast_3d.is_colliding():
    Global.enemy_health -= 1

    func _on_timer_timeout():

    Global.enemy_health = 100`

    the enemy script has the folowing code:
    `func _physics_process(delta):

    if Global.enemy_health <= 0:
    self.queue_free()`

    There is your problem: Global.enemy_health

    You have a single (global) health variable that is shared among all enemies. If you reduce the health variable, you reduce the health of every enemy at the same time.

    Solution: Remove Global.enemy_health and instead declare a health variable within the enemy script. Your player script will also have to get the object that your raycast is colliding with and check if it is an enemy and if yes decrease the enemies health.

      Yeah that is what I initially meant, it sounded like all enemies might be sharing the same global health value.

      Zini If I am removing the global variable, how would I go about changing the enemy's health value when the enemy health variable is in the enemy script, and isn't connected to the the player script.

      • Zini replied to this.

        Huh? You are already accessing variables from another instance in your code. Global.enemy_health. Global is the object, enemy_health the variable. The only difference is that you need to get the object from the function I linked instead of using an autoload.

        janieldoohick123

        • Add something like a health property to your enemy class at initialize it with a default value: var health := 3 or something like that.
        • At some point where you check if you collided with an enemy or if an enemy was hit you get a reference to that enemy. Probably from the raycast.
        • Just access its health property like you do with enemy.position in your code above: enemy.health -= 1