回到Unity3D中,我们写一个简单的例子,Test.cs委托Log.cs 办一件事情,当Log.cs办完后在Test.cs回调委托的方法。代码比较简单我们直接将Test.cs Log.cs 绑在摄像机上,运行就能看到效果。。上代码!!!
Log.cs
using UnityEngine; using System.Collections; public class Log :MonoBehaviour { public delegate void DoOnething(string str); public static event DoOnething doOne; public delegate void DoTwothing(string str); public static event DoTwothing doTwo; void Start () { if(doOne != null) { doOne("yusong"); } if(doTwo != null) { doTwo("momo"); } } }
我解释一下。委托的标识符就是delegate ,上述代码的DoOnething(string str) DoTwothing(string str)就是委托完毕后回调的方法名称,doOne doTwo这两个是委托的事件,在Start方法中通过委托的事件将委托的参数传递进去即可实现委托。在开发中应该有一个专门用来委托的类,在DoOne DoTwo方法之上应该执行对应对托的相关代码。不一定是在Start方法中,静态调用对象皆可。
接着再看看Test.cs
using UnityEngine; using System.Collections; public class Test : MonoBehaviour { void OnEnable() { Log.doOne += DoOnething; Log.doTwo += DoTwothing; } void OnDisable() { Log.doOne -= DoOnething; Log.doTwo -= DoTwothing; } public void DoOnething(string str) { Debug.Log("DoOnething " + str); } public void DoTwothing(string str) { Debug.Log("DoTwothing " + str); } }
在OnEnabel和OnDisable中启动与关闭委托,这也是为什么Log.cs中要判断一下委托是否为空。如果为空的话是会有错误的。比如
Log.doOne += DoOnething;
这段代码的意思就是为委托事件赋值,让本类的DoOnethine(string str)方法接受委托传递回来的事件,这里起到一个回调的作用。
Log.doOne -= DoOnething;
就是释放当前的委托事件,因为Log.doOne是一个静态类型的变量,不用的时候把他关掉,一旦关掉后,DoOnething方法就接收不到回调信息了,除非再次 += 添加。
最后就是当Log.cs中调用 doOne(“yusong”);的时候,实际上就是回调Test.cs中的 DoOnething(string str);
运行一下看看效果大家就明白啦。
本文比较简单,也没什么代码。纯属帮忙写点东西,欢迎大家讨论!!
关于详细代理和事件的区别,下面有篇文章,写的很不错,转给大家。