1.直接监听 用的少
void OnClick()
{
Debug.Log("Button is Click!!!");
}
2.添加事件监听脚本UIEventTriggert
Component—>NGUI —>interactiont—>UIEventTriggert 这样就能添加Ui内部行为事件监听 interactiont会监听次游戏体的行为,自动触发相应的事件,只需将该事件发生时需要执行的游戏体拖到相应的位置,选择相应的方法,值得注意的是 该方法必须是public 类型。
3.使用 UIEventListener
Component—>NGUI —>interactiont—>UIEventListener (此脚本没有必要添加到“button”游戏体对象上,可以进源码查看,自动添加的)
void Start () {
obj = GameObject.Find("Button");
UIEventListener.Get(obj).onClick = ButtonClick;
}
//计算按钮的点击事件
void ButtonClick(GameObject button)
{
GameModel.getInstance().scencemodel.level = "play";
obj.GetComponent<ClickIn>().OnclickIn();//
}
UIEventListener 可以监听的事件和UIEventTriggert是一样多的
public delegate void VoidDelegate (GameObject go);
public VoidDelegate onSubmit;
public VoidDelegate onClick;
public VoidDelegate onDoubleClick;
public BoolDelegate onHover;
public BoolDelegate onPress;
public BoolDelegate onSelect;
public FloatDelegate onScroll;
public VoidDelegate onDragStart
public VectorDelegate onDrag;
public VoidDelegate onDragOver;
public VoidDelegate onDragOut
;public VoidDelegate onDragEnd;
public ObjectDelegate onDrop;
public KeyCodeDelegate onKey;
public BoolDelegate onTooltip;
实际上onXXXX都是 VoidDelegate 句柄 函数方法指针 当然也有个别的需要更多的参数也就是不一样了
当游戏体Butten触发点击事件时 ButtenClick 自动触发,总的来说这种方法不适合用GameObject.Find(),倘若这是在同一个Window下的内部事件 强烈建议使用外部拖拽赋值实现。
4.使用EventDelegate
此类并没有继承自MonoBehaviour 古在菜单项不能找到他,进入源码你会发现其实就是对Delegate 的封装,让其更加安全可靠,建议使用(此脚本不方便监听NGUI事件,用的更多是游戏体之间的传递,或者直接和UImanager 打交道)。
public UIPopupList UserList=null;
public void Start () {
Lsb=gameObject.GetComponent<LoginSenceBusiness>();
EventDelegate.Add(UserList.onChange, setlogin);
}
void setlogin(){
if (UserList.value == "other") {
setLoginPanelTrue();
GuestUserLoginPanel.transform.position=new Vector3(500,0,0);
}
}
UserList 在外边赋值,当其 onChange 事件出发时 自动执行setlogin 方法
public delegate void Callback();
static public EventDelegate Add (List<EventDelegate> list, Callback callback)
这是源码 不难看出 它只是将 callback 放进了 list。源码还有其他的重载方法,满足用户不同需求。
EventDelegate还有其他的用法比喻
void OnMouseUpAsButton()
{
if (mousePressTime > 0.2) {
return;
}
if (UICamera.hoveredObject==null) {
scaleEffect.Play(click);
}
}
void OnMouseDrag(){
mousePressTime += Time.fixedDeltaTime;
}
void OnMouseDown(){
mousePressTime = 0;
}
public void click()
{
GameData.getInstance ().M_ui_data.M_BuildingData.CurrentBuilding = m_BuildingName;
OperateWindowSystem.Instance.ShowUI();
EventDelegate.Execute(ClickedEvent);
}
public List<EventDelegate> ClickedEvent = new List<EventDelegate>();
输入Size 拖进游戏体 MMethod Name是MethodInfo 的实例,涉及到映射,笔者能力有限,目测在这个地方 输入方法名就可以了,此方法不管是公有还是私有都能被调用。