Health/Assets/Scripts/UI/UIPanelBase.cs

66 lines
1.8 KiB
C#

using System;
using System.Linq;
using UnityEngine.UI;
public abstract class UIPanelBase : UIBase
{
private void OnEnable()
{
Bind();
}
private void OnDisable()
{
UnBind();
}
protected void Bind()
{
Type type = GetType();
var methods = type.GetMethods();
foreach (var method in methods)
{
var attributes = method.GetCustomAttributes(typeof(UIButtonOnClickAttribute), true);
if (attributes.Length == 0)
continue;
var attribute = attributes[0] as UIButtonOnClickAttribute;
var btns = transform.GetComponentsInChildren<Button>().ToList();
var button = btns.Find(btns => btns.name == attribute.ButtonName);
if (button == null)
continue;
button.onClick.AddListener(() => { method.Invoke(this, null); });
}
}
protected void UnBind()
{
Type type = GetType();
var methods = type.GetMethods();
foreach (var method in methods)
{
var attributes = method.GetCustomAttributes(typeof(UIButtonOnClickAttribute), true);
if (attributes.Length == 0)
continue;
var attribute = attributes[0] as UIButtonOnClickAttribute;
var btns = transform.GetComponentsInChildren<Button>().ToList();
var button = btns.Find(btns => btns.name == attribute.ButtonName);
if (button == null)
continue;
button.onClick.RemoveListener(() => { method.Invoke(this, null); });
}
}
}
public class UIButtonOnClickAttribute : Attribute
{
public string ButtonName { get; private set; }
public UIButtonOnClickAttribute(string button)
{
ButtonName = button;
}
}