多个监听对象触发一个委托方法~~~~~~~~~~~~~~~~~~~~~~
能够很好的使用委托,会很好的提高代码运行效率
下面看一下监听代码:监听主要包括定义委托,和委托方法的调用
using UnityEngine;
using System.Collections;
public class EventListener : MonoBehaviour {
public delegate void VoidOnMouseOver (GameObject _go);//参数可修改,传出到所用脚本
public delegate void VoidOnMouseDown (GameObject _go);
public delegate void VoidOnMouseUp (GameObject _go);
public delegate void VoidOnMouseDrag (GameObject _go);
public delegate void VoidOnMouseEnter(GameObject _go);
public delegate void VoidOnMouseExit (GameObject _go);
public VoidOnMouseOver _onMouseOver;
public VoidOnMouseDown _onMouseDown;
public VoidOnMouseOver _onMouseUp;
public VoidOnMouseDown _onMouseDrag;
public VoidOnMouseOver _onMouseEnter;
public VoidOnMouseDown _onMouseExit;
//当鼠标滑过
void OnMouseOver() { if(_onMouseOver != null) { _onMouseOver(gameObject); } }
//当鼠标按下
void OnMouseDown() { if(_onMouseDown != null) { _onMouseDown(gameObject); } }
//当鼠标弹起
void OnMouseUp() { if(_onMouseUp != null) { _onMouseUp (gameObject); } }
//当鼠标拖拽
void OnMouseDrag() { if(_onMouseDrag != null) { _onMouseDrag(gameObject); } }
//当鼠标进入
void OnMouseEnter() { if(_onMouseEnter!= null) { _onMouseEnter(gameObject); } }
//当鼠标退出
void OnMouseExit() { if(_onMouseExit != null) { _onMouseExit (gameObject); } }
//获取_go对象身上的监听脚本
public static EventListener Get(GameObject _go)
{
EventListener _eventListence = _go.GetComponent<EventListener>();
if(_eventListence == null) { _eventListence = _go.AddComponent<EventListener>(); }
return _eventListence;
}
}
下面看委托注册代码:主要完成委托的注册,和方法体的定义
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
public GameObject _target;
void Start ()
{
EventListener _eventListence = EventListener.Get(_target);
_eventListence._onMouseEnter = DebugData;
}
void DebugData(GameObject _go)//_go用来获取监听对象,(参数用来获取监听对象上的信息)
{
Debug.Log(_go.name);
}
}
【参考】http://www.cnblogs.com/OpenCoder/archive/2009/09/23/1572646.html
委托一般为无返回值类型void
public event GeneralEventHandler NumberChanged {add{...}remove{...}}语句便是事件访问器
事件 是为了封装委托,更易使用。事件隐式声明中,为私有委托实例,所以注册端无法触发
事件就是一个狭义的委托,也就是事件是一个用于事件驱动模型的专用委托.
通俗的讲,委托你可以在客户代码中直接调用委托来激发委托指向的函数,而事件不可以,事件的触发只能由服务代码自己触发
也就是说在你的代码里委托你不但可以安排谁是它的调用函数,还可以直接调用它,而事件不能直接调用,只能通过某些操作触发