Health Component
Type: GeneralTracks health for any node. Emits signals when damaged, healed or dead, so the rest of your scene can react.
Setup
- Save the script as health_component.gd.
- Add a Node as a child of your player or enemy and attach the script.
- Set Max Health in the Inspector.
- Connect the died signal to whatever should happen on death, for example queue_free on the parent.
Code
GDScript
class_name HealthComponent
extends Node
## Tracks health for its parent. Emits signals when damaged, healed or dead.
signal health_changed(current: int, maximum: int)
signal died
@export var max_health: int = 100
var health: int
func _ready() -> void:
health = max_health
func damage(amount: int) -> void:
if amount <= 0 or is_dead():
return
health = maxi(health - amount, 0)
health_changed.emit(health, max_health)
if health == 0:
died.emit()
func heal(amount: int) -> void:
if amount <= 0 or is_dead():
return
health = mini(health + amount, max_health)
health_changed.emit(health, max_health)
func is_dead() -> bool:
return health <= 0Usage example
GDScript
# enemy.gd
@onready var health: HealthComponent = $HealthComponent
func _ready() -> void:
health.died.connect(queue_free)
func take_hit() -> void:
health.damage(25)