Skip to content
GodotComponents
← Back to components
A character with a health bar above it that drops in steps until it is empty.

Health Component

Type: General

Tracks health for any node. Emits signals when damaged, healed or dead, so the rest of your scene can react.

Setup

  1. Save the script as health_component.gd.
  2. Add a Node as a child of your player or enemy and attach the script.
  3. Set Max Health in the Inspector.
  4. 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 <= 0

Usage example

GDScript
# enemy.gd
@onready var health: HealthComponent = $HealthComponent


func _ready() -> void:
	health.died.connect(queue_free)


func take_hit() -> void:
	health.damage(25)