Unity_Learn/Assets/Scripts/UI/UI_Base.cs

64 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Object = UnityEngine.Object;
public abstract class UI_Base : MonoBehaviour
{
Dictionary<Type, Object[]> _objects = new Dictionary<Type, Object[]>();
public abstract void Init();
protected void Bind<T>(Type type) where T : Object
{
string[] names = Enum.GetNames(type);
Object[] objects = new Object[names.Length];
_objects.Add(typeof(T), objects);
for (int i = 0; i < names.Length; i++)
{
if(typeof(T) == typeof(GameObject))
{
objects[i] = Util.FindChild(gameObject, names[i],true);
}
else
{
objects[i] = Util.FindChild<T>(gameObject, names[i],true);
}
}
}
protected T Get<T>(int idx) where T : Object
{
Object[] objects = null;
if (_objects.TryGetValue(typeof(T), out objects) == false || idx < 0 || idx >= objects.Length)
return null;
return objects[idx] as T;
}
protected GameObject GetObject(int idx) { return Get<GameObject>(idx); }
protected TextMeshProUGUI GetText(int idx) { return Get<TextMeshProUGUI>(idx); }
protected Button GetButton(int idx) { return Get<Button>(idx); }
protected Image GetImage(int idx) { return Get<Image>(idx); }
public static void BindUIEvent(GameObject go, Action<PointerEventData> action, Define.UIEvent type = Define.UIEvent.Click)
{
UI_EventHandler evt = Util.GetOrAddComponent<UI_EventHandler>(go);
switch (type)
{
case Define.UIEvent.Click:
evt.OnClickHandler -= action;
evt.OnClickHandler += action;
break;
case Define.UIEvent.Drag:
evt.OnDragHandler -= action;
evt.OnDragHandler += action;
break;
}
}
}