Files
Fishing2/Assets/Scripts/UI/Common/Panel/Information/Alert.cs
Bob.Song 830cf3c354 settings
2026-03-25 17:07:05 +08:00

131 lines
3.6 KiB
C#

using System.Collections.Generic;
using FairyGUI;
using NBC;
namespace NBF
{
public class Alert : INoticeComponent
{
private static bool _init;
private const int Gap = 8;
private const int ItemWidth = 300;
private const int ItemHeight = 42;
private float _startY;
private float _startX;
private const int LimitCount = 6; //显示条数上限
private GObjectPool _noticePool;
private static readonly Queue<string> _msgArr = new();
protected GComponent ContentPane;
public static void Show(string msg)
{
if (string.IsNullOrEmpty(msg)) return;
Log.Info($"显示一个notice={msg}");
if (!_init)
{
NoticesPanel.TryAddNoticeComponent(new Alert());
}
_msgArr.Enqueue(msg);
}
public void OnInit(GComponent root)
{
_init = true;
ContentPane = root;
_noticePool = new GObjectPool(ContentPane.container.cachedTransform);
_startY = GRoot.inst.height - ItemHeight - Gap - 90;
_startX = GRoot.inst.width * 0.5f - ItemWidth * 0.5f;
}
public void OnUpdate()
{
if (_msgArr.Count > 0)
{
var msg = _msgArr.Dequeue();
ShowOnceNotice(msg);
//旧的向上移动
var count = ContentPane.numChildren - 1;
for (int i = 0; i < count; i++)
{
GObject obj = ContentPane.GetChildAt(i);
if (obj != null)
{
SetObjRise(obj);
}
}
RemoveLimitMsg();
}
}
public void OnDestroy()
{
_noticePool.Clear();
}
private void ShowOnceNotice(string msg)
{
var item = GetFromPool(AlertItem.URL) as AlertItem;
if (item == null) return;
item.SetData(msg);
item.x = _startX;
item.y = _startY;
item.alpha = 1;
//显示在固定区域 两秒后消失
item.TweenFade(0, 0.5f).SetDelay(5).OnComplete(() => { ReturnToPool(item); });
}
private void SetObjRise(GObject item)
{
item.TweenMoveY(item.y - item.height - 10, 0.2f).SetEase(EaseType.QuintInOut);
}
private void RemoveLimitMsg()
{
var count = ContentPane.numChildren;
if (count > LimitCount)
{
for (int i = 0; i < count - LimitCount; i++)
{
GObject obj = ContentPane.GetChildAt(i);
if (obj != null)
{
if (GTween.IsTweening(obj))
{
GTween.Kill(obj, true);
}
else
{
ReturnToPool(obj);
}
}
}
}
}
private GObject GetFromPool(string url)
{
var ret = _noticePool.GetObject(url);
if (ret == null) return null;
ret.visible = true;
ContentPane.AddChild(ret);
GTween.GetTween(ret, TweenPropType.Y)?.Kill();
return ret;
}
private void ReturnToPool(GObject obj)
{
ContentPane.RemoveChild(obj);
_noticePool.ReturnObject(obj);
}
}
}