Files
Emberwild/Assets/GAME/Script/UI/NotificationItemUI.cs
T
2026-06-22 16:18:34 +02:00

111 lines
3.3 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using TMPro;
using DG.Tweening;
using Ashwild.Inventory;
namespace Ashwild.UI
{
public class NotificationItemUI : MonoBehaviour
{
[Header("References")]
[SerializeField] private Image iconImage;
[SerializeField] private TextMeshProUGUI labelText; // item name only
[SerializeField] private TextMeshProUGUI numberText; // signed context: +N / -N
[SerializeField] private CanvasGroup canvasGroup;
[SerializeField] private RectTransform rectTransform;
private ItemData itemData;
private int totalQuantity;
private float hideTimer;
private bool isHiding;
private Tweener fadeTween;
private Tweener slideTween;
private Tweener punchTween;
public ItemData ItemData => itemData;
public RectTransform RectTransform => rectTransform;
// A notification is either a gain (+) or a loss (-); merging only happens within the same direction.
public bool IsGain => totalQuantity >= 0;
public void Initialize(ItemData item, int signedQuantity, Color numberColor, float displayDuration, float slideInDuration, Ease slideInEase)
{
itemData = item;
totalQuantity = signedQuantity;
hideTimer = displayDuration;
isHiding = false;
if (iconImage != null)
iconImage.sprite = item.Icon;
if (numberText != null)
numberText.color = numberColor;
UpdateLabel();
canvasGroup.alpha = 0f;
fadeTween = canvasGroup.DOFade(1f, slideInDuration).SetEase(Ease.OutQuad);
}
public void AddQuantity(int signedAmount, float displayDuration)
{
totalQuantity += signedAmount;
UpdateLabel();
hideTimer = displayDuration;
if (isHiding)
{
isHiding = false;
fadeTween?.Kill();
slideTween?.Kill();
canvasGroup.alpha = 1f;
}
punchTween?.Kill();
if (iconImage != null)
punchTween = iconImage.transform.DOPunchScale(Vector3.one * 0.15f, 0.25f, 5, 0.5f);
}
private void UpdateLabel()
{
if (labelText != null)
labelText.text = itemData.ItemName;
if (numberText != null)
numberText.text = (totalQuantity >= 0 ? "+" : "-") + Mathf.Abs(totalQuantity);
}
private void Update()
{
if (isHiding) return;
hideTimer -= Time.deltaTime;
if (hideTimer <= 0f)
Hide();
}
public void Hide()
{
if (isHiding) return;
isHiding = true;
fadeTween?.Kill();
slideTween?.Kill();
fadeTween = canvasGroup.DOFade(0f, 0.3f).SetEase(Ease.InQuad);
slideTween = rectTransform.DOAnchorPosX(rectTransform.anchoredPosition.x - 200f, 0.3f)
.SetEase(Ease.InQuad)
.OnComplete(() => Destroy(gameObject));
}
private void OnDestroy()
{
fadeTween?.Kill();
slideTween?.Kill();
punchTween?.Kill();
}
}
}