first commit
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using OTGIntegrated.Core;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace OTGIntegrated.UI
|
||||
{
|
||||
public sealed class NotificationUI : MonoBehaviour
|
||||
{
|
||||
public RectTransform stackRoot;
|
||||
public Font uiFont;
|
||||
public float visibleSeconds = 2.4f;
|
||||
public int maxMessages = 5;
|
||||
|
||||
private readonly Queue<GameObject> activeMessages = new Queue<GameObject>();
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
GameEvents.OnNotificationRequested += Show;
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
GameEvents.OnNotificationRequested -= Show;
|
||||
}
|
||||
|
||||
public void Show(string message)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message) || stackRoot == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
GameObject root = new GameObject("Notification", typeof(RectTransform), typeof(CanvasGroup), typeof(Image));
|
||||
root.transform.SetParent(stackRoot, false);
|
||||
root.GetComponent<RectTransform>().sizeDelta = new Vector2(520f, 42f);
|
||||
root.GetComponent<Image>().color = new Color(0.05f, 0.06f, 0.08f, 0.86f);
|
||||
|
||||
Text text = CreateText(root.transform, "Text", message, 16, TextAnchor.MiddleCenter);
|
||||
text.rectTransform.anchorMin = Vector2.zero;
|
||||
text.rectTransform.anchorMax = Vector2.one;
|
||||
text.rectTransform.offsetMin = new Vector2(12f, 0f);
|
||||
text.rectTransform.offsetMax = new Vector2(-12f, 0f);
|
||||
|
||||
activeMessages.Enqueue(root);
|
||||
while (activeMessages.Count > maxMessages)
|
||||
{
|
||||
GameObject old = activeMessages.Dequeue();
|
||||
if (old != null)
|
||||
{
|
||||
Destroy(old);
|
||||
}
|
||||
}
|
||||
|
||||
StartCoroutine(FadeAndDestroy(root));
|
||||
}
|
||||
|
||||
private IEnumerator FadeAndDestroy(GameObject root)
|
||||
{
|
||||
CanvasGroup group = root.GetComponent<CanvasGroup>();
|
||||
float age = 0f;
|
||||
while (age < visibleSeconds)
|
||||
{
|
||||
age += Time.deltaTime;
|
||||
if (group != null)
|
||||
{
|
||||
group.alpha = age < visibleSeconds - 0.45f ? 1f : Mathf.Clamp01((visibleSeconds - age) / 0.45f);
|
||||
}
|
||||
|
||||
yield return null;
|
||||
}
|
||||
|
||||
if (root != null)
|
||||
{
|
||||
Destroy(root);
|
||||
}
|
||||
}
|
||||
|
||||
private Text CreateText(Transform parent, string name, string value, int fontSize, TextAnchor anchor)
|
||||
{
|
||||
GameObject textObject = new GameObject(name, typeof(RectTransform), typeof(Text));
|
||||
textObject.transform.SetParent(parent, false);
|
||||
Text text = textObject.GetComponent<Text>();
|
||||
UITheme.ApplyText(text, uiFont, fontSize, anchor);
|
||||
text.text = value;
|
||||
return text;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user