2026-04-16 14:57:19 +08:00

112 lines
3.0 KiB
C#

using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
using Kill.Managers;
namespace Kill.UI.Components
{
public class ToastUI : MonoBehaviour
{
public static ToastUI Instance { get; private set; }
public RectTransform toastPanel;
public Text messageText;
public Vector2 showPosition = new Vector2(0, -100);
public Vector2 hidePosition = new Vector2(0, -200);
public float slideInDuration = 0.3f;
public float stayDuration = 2f;
public float slideOutDuration = 0.3f;
public Ease easeType = Ease.OutBack;
private Tween currentTween;
private void Awake()
{
if (Instance == null)
{
Instance = this;
Initialize();
}
else
{
Destroy(gameObject);
}
}
private void Initialize()
{
if (toastPanel != null)
{
toastPanel.anchoredPosition = hidePosition;
toastPanel.gameObject.SetActive(false);
}
}
public static void Show(string languageKey)
{
if (Instance == null) return;
Instance.ShowInternal(languageKey);
}
public static void ShowText(string text)
{
if (Instance == null) return;
Instance.ShowInternal(text, false);
}
private void ShowInternal(string keyOrText, bool isLanguageKey = true)
{
currentTween?.Kill();
string message = isLanguageKey ? GetLanguageText(keyOrText) : keyOrText;
if (messageText != null)
messageText.text = message;
if (toastPanel == null) return;
toastPanel.gameObject.SetActive(true);
Sequence sequence = DOTween.Sequence();
sequence.Append(toastPanel.DOAnchorPos(showPosition, slideInDuration).SetEase(easeType));
sequence.AppendInterval(stayDuration);
sequence.Append(toastPanel.DOAnchorPos(hidePosition, slideOutDuration).SetEase(Ease.InBack)
.OnComplete(() => toastPanel.gameObject.SetActive(false)));
currentTween = sequence;
}
public static void Hide()
{
if (Instance == null) return;
Instance.HideInternal();
}
private void HideInternal()
{
currentTween?.Kill();
if (toastPanel != null)
{
toastPanel.DOAnchorPos(hidePosition, slideOutDuration)
.SetEase(Ease.InBack)
.OnComplete(() => toastPanel.gameObject.SetActive(false));
}
}
private string GetLanguageText(string key)
{
return LanguageManager.Instance != null
? LanguageManager.Instance.GetLanguage(key)
: key;
}
private void OnDestroy()
{
if (Instance == this) Instance = null;
currentTween?.Kill();
}
}
}