using System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthSystem : MonoBehaviour { public int maxHealth = 100; public int currentHealth; public delegate void OnHealthChanged(int currentHealth, int maxHealth); public event OnHealthChanged onHealthChanged; public delegate void OnDeath(); public event OnDeath onDeath; public void Start() { currentHealth = maxHealth; // Initialize health onHealthChanged?.Invoke(currentHealth, maxHealth); // Notify UI or other systems } public void TakeDamage(int damage) { currentHealth -= damage; if (currentHealth <= 0) { currentHealth = 0; Die(); } onHealthChanged?.Invoke(currentHealth, maxHealth); // Update health bar or UI } public void Heal(int amount) { currentHealth = Mathf.Min(currentHealth + amount, maxHealth); // Ensure health doesn't exceed max onHealthChanged?.Invoke(currentHealth, maxHealth); // Update health bar or UI } public void Die() { onDeath?.Invoke(); // Trigger death event // You can trigger death-related logic here or in the subscribed listener } public int GetCurrentHealth() { return currentHealth; } public int GetMaxHealth() { return maxHealth; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter