using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections.Generic;
namespace UIWidgets
{
[RequireComponent(typeof(RectTransform))]
///
/// Modal helper for UI widgets.
/// modalKey = ModalHelper.Open(this, modalSprite, modalColor);
/// //...
/// ModalHelper.Close(modalKey);
///
public class ModalHelper : MonoBehaviour, ITemplatable, IPointerClickHandler
{
bool isTemplate = true;
///
/// Gets a value indicating whether this instance is template.
///
/// true if this instance is template; otherwise, false.
public bool IsTemplate {
get {
return isTemplate;
}
set {
isTemplate = value;
}
}
///
/// Gets the name of the template.
///
/// The name of the template.
public string TemplateName {
get;
set;
}
UnityEvent OnClick = new UnityEvent();
static Templates Templates = new Templates();
static Dictionary used = new Dictionary();
static string key = "ModalTemplate";
void OnDestroy()
{
Templates.Delete(key);
}
///
/// Raises the pointer click event.
///
/// Event data.
public void OnPointerClick(PointerEventData eventData)
{
if (eventData.button!=PointerEventData.InputButton.Left)
{
return;
}
OnClick.Invoke();
}
///
/// Create modal helper with the specified parent, sprite and color.
///
/// Parent.
/// Sprite.
/// Color.
/// onClick callback
/// Modal helper index
public static int Open(MonoBehaviour parent, Sprite sprite = null, Color? color = null, UnityAction onClick = null)
{
//check if in cache
if (!Templates.Exists(key))
{
Templates.FindTemplates();
CreateTemplate();
}
var modal = Templates.Instance(key);
modal.transform.SetParent(Utilites.FindTopmostCanvas(parent.transform), false);
modal.gameObject.SetActive(true);
modal.transform.SetAsLastSibling();
var rect = modal.transform as RectTransform;
rect.sizeDelta = new Vector2(0, 0);
rect.anchorMin = new Vector2(0, 0);
rect.anchorMax = new Vector2(1, 1);
rect.anchoredPosition = new Vector2(0, 0);
var img = modal.GetComponent();
if (sprite!=null)
{
img.sprite = sprite;
}
if (color!=null)
{
img.color = (Color)color;
}
modal.OnClick.RemoveAllListeners();
if (onClick!=null)
{
modal.OnClick.AddListener(onClick);
}
used.Add(modal.GetInstanceID(), modal);
return modal.GetInstanceID();
}
///
/// Creates the template.
///
static void CreateTemplate()
{
var template = new GameObject(key);
var modal = template.AddComponent();
template.AddComponent();
Templates.Add(key, modal);
template.gameObject.SetActive(false);
}
///
/// Close modal helper with the specified index.
///
/// Index.
public static void Close(int index)
{
if ((used!=null) && (used.ContainsKey(index)))
{
used[index].OnClick.RemoveAllListeners();
Templates.ToCache(used[index]);
used.Remove(index);
}
}
}
}