using UnityEngine; using BigFloatNumerics; public class HpBarHandler : MonoBehaviour, IOwnedComponent { [SerializeField] Transform spawnPosition; [SerializeField] ExtendSlider barPrefab; public Character Owner { get; private set; } StatData hpStat; Camera mainCamera; Camera uiCamera; RectTransform barRoot; ExtendSlider barInstance; public void Initialize(Character owner) { Owner = owner; Owner.Data.TryGetStat(StatID.Hp, out hpStat); mainCamera = Camera.main; uiCamera = GameObject.FindGameObjectWithTag("UICamera").GetComponent(); barRoot = GameObject.FindGameObjectWithTag("HpBarRoot").GetComponent(); barInstance = Instantiate(barPrefab, barRoot); } private void OnDestroy() { if (Owner == null) return; if(barInstance != null && barInstance.gameObject != null) Destroy(barInstance.gameObject); } private void Update() { if (barInstance == null) return; if (Owner != null && hpStat != null) { barInstance.SetRate((BigFloat)Owner.CurrentHp / hpStat.Value); } } private void LateUpdate() { if(barInstance == null) return; var screenPos = mainCamera.WorldToScreenPoint(spawnPosition.position); RectTransformUtility.ScreenPointToLocalPointInRectangle(barRoot, screenPos, uiCamera, out Vector2 localPos); barInstance.transform.localPosition = localPos; } }