C#中的委托和事件

来源:互联网 发布:电脑桌面设置软件 编辑:程序博客网 时间:2024/04/29 05:54
委托和事件一般是一起使用的,事件也是特殊的委托,事件和委托的的区别有:

 1.委托可以使用 ‘=’ 来赋值而事件不可以

 2.委托可以在类的外部调用(最好不要),而事件只可以在类内部调用

 3.委托是一个类型,而事件是用来修饰对象的

 委托在U3D中提供了一种脚本之间通信的方式,一般也用来起回调的作用,就像传参数一样,可以传递方法。

 

例如声明两个类cube.clsss和sphere.class

 1 using UnityEngine; 2 using System.Collections; 3  4 public class cube: MonoBehaviour { 5  6     public delegate void deleFunction(GameObject str); 7  8     public static event deleFunction eventFunction; 9 10     // Use this for initialization11     void Start () {12     13     }14     15     // Update is called once per frame16     void Update () {17     18     }19 20     void OnMouseOver(){21 22         if(eventFunction!= null){23 24             eventFunction(this.gameObject);25         }26     }27 }
View Code
 1 using UnityEngine; 2 using System.Collections; 3  4 public class sphere: MonoBehaviour { 5  6  7  8     // Use this for initialization 9     void Start () {10 11         cube.eventFunction += Test;12     }13     14     // Update is called once per frame15     void Update () {16     17     }18 19     void Test(GameObject t){20 21         this.renderer.material.color = Color.red;        22         t.transform.Rotate(transform.forward);23     }24 }
View Code

在unity中创建cube和sphere,将脚本托给相应物体。运行游戏会发现

在游戏开始的时候,sphere脚本注册cube产生的委托,来执行Test函数,

当鼠标移入cube物体上时,会判断时间是否有人注册,如果有人注册会将cube的gameobject传个注册函数并执行sphere里面的注册函数。

这样做也就实现了用cube的OnMouseOver事件来触发sphere物体的Test函数。

 

0 0
原创粉丝点击