56 lines
2.0 KiB
C#
56 lines
2.0 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI; // ⭐ Image 컴포넌트 사용을 위해 필수!
|
|
using TMPro;
|
|
|
|
public class HPUibar : MonoBehaviour
|
|
{
|
|
[Header("--- 참조 ---")]
|
|
[SerializeField] private MonoBehaviour healthSource;
|
|
|
|
// ⭐ [수정] Slider 대신 Image 타입을 사용합니다.
|
|
[SerializeField] private Image hpFillImage;
|
|
[SerializeField] private TextMeshProUGUI hpText;
|
|
|
|
private void Start()
|
|
{
|
|
// 1. 체력 소스 연결 (플레이어, 더미, 몬스터 등 모두 대응)
|
|
if (healthSource is PlayerHealth ph) ph.OnHealthChanged += UpdateUI;
|
|
else if (healthSource is TrainingDummy td) td.OnHealthChanged += UpdateUI;
|
|
else if (healthSource is EnemyHealth eh) eh.OnHealthChanged += UpdateUI;
|
|
else if (healthSource is MonsterClass mc) mc.OnHealthChanged += UpdateUI;
|
|
|
|
// 시작 시 풀피로 설정
|
|
if (hpFillImage != null) hpFillImage.fillAmount = 1f;
|
|
}
|
|
|
|
private void UpdateUI(float current, float max)
|
|
{
|
|
// 2. ⭐ [핵심 수정] 이미지의 fillAmount를 0 ~ 1 사이 값으로 조절합니다.
|
|
if (hpFillImage != null && max > 0)
|
|
{
|
|
hpFillImage.fillAmount = current / max;
|
|
}
|
|
|
|
// 텍스트 업데이트
|
|
if (hpText != null)
|
|
{
|
|
hpText.text = $"{Mathf.CeilToInt(current)} / {Mathf.CeilToInt(max)}";
|
|
}
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
// 체력바가 항상 카메라를 바라보게 함 (빌보드 효과)
|
|
if (Camera.main != null)
|
|
transform.LookAt(transform.position + Camera.main.transform.forward);
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
// 이벤트 해제 (메모리 누수 방지)
|
|
if (healthSource is PlayerHealth ph) ph.OnHealthChanged -= UpdateUI;
|
|
else if (healthSource is TrainingDummy td) td.OnHealthChanged -= UpdateUI;
|
|
else if (healthSource is EnemyHealth eh) eh.OnHealthChanged -= UpdateUI;
|
|
else if (healthSource is MonsterClass mc) mc.OnHealthChanged -= UpdateUI;
|
|
}
|
|
} |