Files
2026-06-26 22:41:39 +05:30

62 lines
1.4 KiB
C#

using UnityEngine;
using UnityEngine.UI;
public class SegmentedHealthUI : MonoBehaviour
{
public Image[] healthBoxes; // assign 15 boxes
public Health playerHealth; // drag player here
private int maxSegments;
void Start()
{
maxSegments = healthBoxes.Length;
InvokeRepeating(nameof(FindPlayerHealth), 0f, 0.5f);
}
void FindPlayerHealth()
{
PlayerControllerNewRohan player =
FindObjectOfType<PlayerControllerNewRohan>();
if (player == null)
{
Debug.LogWarning("Player not found.");
return;
}
playerHealth = player.GetComponent<Health>();
if (playerHealth == null)
{
Debug.LogWarning("Health component not found.");
return;
}
playerHealth.OnHealthChanged += UpdateHealthUI;
UpdateHealthUI(
playerHealth.currentHealth,
playerHealth.maxHealth
);
}
void UpdateHealthUI(float current, float max)
{
float healthPercent = current / max;
int activeBoxes = Mathf.CeilToInt(healthPercent * maxSegments);
for (int i = 0; i < healthBoxes.Length; i++)
{
healthBoxes[i].enabled = i < activeBoxes;
}
}
void OnDestroy()
{
if (playerHealth != null)
playerHealth.OnHealthChanged -= UpdateHealthUI;
}
}