Files
BabyVideo/Assets/Scripts/UI/Notices.cs
2026-02-09 20:10:14 +08:00

141 lines
3.9 KiB
C#

// 本脚本只在不存在时会生成一次。已存在不会再次生成覆盖
using System.Collections.Generic;
using FairyGUI;
using UnityEngine;
using NBC;
using UIPanel = NBC.UIPanel;
namespace NBF
{
public partial class Notices : UIPanel
{
private static bool _isOpen;
private static readonly Queue<string> MsgArr = new();
private GObjectPool _noticePool;
private string _itemUrl;
private float _startY;
private const int LimitCount = 3; //显示条数上限
public static void Show(string msg)
{
if (string.IsNullOrEmpty(msg)) return;
Log.Info($"显示一个notice={msg}");
if (!_isOpen)
{
UI.Inst.OpenUI<Notices>();
}
MsgArr.Enqueue(msg);
}
protected override void OnInit()
{
ContentPane.sortingOrder = UIDef.UIOrder.Notices;
_startY = GRoot.inst.height / 2;
_itemUrl = UIPackage.GetItemURL(UIDef.Pack.Main, "NoticeItem");
_noticePool = new GObjectPool(ContentPane.container.cachedTransform);
MonoManager.Inst.OnUpdate += OnUpdate;
}
protected override void OnShow()
{
_isOpen = true;
}
protected override 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();
}
}
//region notice
private void ShowOnceNotice(string msg)
{
var item = GetFromPool(_itemUrl).asLabel;
item.title = msg;
item.x = 0;
item.y = _startY;
item.alpha = 1;
//显示在固定区域 两秒后消失
item.TweenFade(0, 0.5f).SetDelay(2).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);
}
// TweenManager.KillTweens(obj, TweenPropType.Alpha, true);
}
}
}
}
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);
}
//endregion
protected override void OnHide()
{
_isOpen = false;
}
protected override void OnDestroy()
{
_noticePool.Clear();
MonoManager.Inst.OnUpdate -= OnUpdate;
}
}
}