Files
2026-02-21 16:45:37 +08:00

99 lines
2.4 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;
namespace UIWidgets
{
[RequireComponent(typeof(RectTransform))]
public class ModalHelper : MonoBehaviour, ITemplatable, IPointerClickHandler, IEventSystemHandler
{
private bool isTemplate = true;
private UnityEvent OnClick = new UnityEvent();
private static Templates<ModalHelper> Templates = new Templates<ModalHelper>();
private static Dictionary<int, ModalHelper> used = new Dictionary<int, ModalHelper>();
private static string key = "ModalTemplate";
public bool IsTemplate
{
get
{
return isTemplate;
}
set
{
isTemplate = value;
}
}
public string TemplateName { get; set; }
private void OnDestroy()
{
Templates.Delete(key);
}
public void OnPointerClick(PointerEventData eventData)
{
OnClick.Invoke();
}
public static int Open(MonoBehaviour parent, Sprite sprite = null, Color? color = null, UnityAction onClick = null)
{
if (!Templates.Exists(key))
{
Templates.FindTemplates();
CreateTemplate();
}
ModalHelper modalHelper = Templates.Instance(key);
modalHelper.transform.SetParent(Utilites.FindCanvas(parent.transform), false);
modalHelper.gameObject.SetActive(true);
modalHelper.transform.SetAsLastSibling();
RectTransform rectTransform = modalHelper.transform as RectTransform;
rectTransform.sizeDelta = new Vector2(0f, 0f);
rectTransform.anchorMin = new Vector2(0f, 0f);
rectTransform.anchorMax = new Vector2(1f, 1f);
rectTransform.anchoredPosition = new Vector2(0f, 0f);
Image component = modalHelper.GetComponent<Image>();
if (sprite != null)
{
component.sprite = sprite;
}
if (color.HasValue)
{
component.color = color.Value;
}
modalHelper.OnClick.RemoveAllListeners();
if (onClick != null)
{
modalHelper.OnClick.AddListener(onClick);
}
used.Add(modalHelper.GetInstanceID(), modalHelper);
return modalHelper.GetInstanceID();
}
private static void CreateTemplate()
{
GameObject gameObject = new GameObject(key);
ModalHelper template = gameObject.AddComponent<ModalHelper>();
gameObject.AddComponent<Image>();
Templates.Add(key, template);
}
public static void Close(int index)
{
if (used != null && used.ContainsKey(index))
{
used[index].OnClick.RemoveAllListeners();
Templates.ToCache(used[index]);
used.Remove(index);
}
}
}
}