UIMouseEvent.cs:
using UnityEngine;
using System;
public abstract class UIMouseEvent : MonoBehaviour
{
public EventHandler<EventArgs> MouseEvent { get; set; }
}
UIEvent.cs:
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Collections;
public class UIEvent
{
public static GameObject FindChild (string objName)
{
GameObject obj = GameObject.Find("quickLoginBtn");
return obj;
}
public static void AddChildMouseClickEvent (string objName, EventHandler<EventArgs> action)
{
AddMouseClickEvent (FindChild (objName), action);
}
public static void AddMouseClickEvent (GameObject obj, EventHandler<EventArgs> action)
{
if (obj != null) {
AddEvent<UIMouseClick> (obj, action);
}
Debug.Log("111111");
}
public static void AddEvent<T> (GameObject obj, EventHandler<EventArgs> action) where T : UIMouseEvent
{
T mouseEvent = obj.GetComponent<T> ();
if (null != mouseEvent) {
GameObject.DestroyImmediate (mouseEvent);
}
mouseEvent = obj.AddComponent<T> ();
mouseEvent.MouseEvent = action;
Debug.Log("22222");
}
public static void AttachEvent ()
{
Debug.Log ("AttachEvent");
AddChildMouseClickEvent ("quickLoginBtn", OnClickStart);
}
private static void OnClickStart (object sender, EventArgs e)
{
Debug.Log("OnClickStart");
}
}
UIMouseClick.cs:
using UnityEngine;
using System;
public class UIMouseClick : UIMouseEvent
{
void OnClick()
{
Debug.Log("hhhhh");
UIEvent.AttachEvent();
if(null != MouseEvent)
MouseEvent(gameObject, null);
}
}
最后把UIMouseClick.cs放到NGUI的button上面就可以了,这个button的名字为“quickLoginBtn”,结果如下: