每一个对象都有SendMessage,BroadcastMessage,SendMessageUpwards 三个发送消息的方法!

1、功能:

执行某个对象中的某个方法!
 
2、实现原理
反射
 
3、参数
参数                       类型                                                  说明
methodName           string                                    The name of the method to call.    // 方法名称
value                      object                                    An optional parameter value to pass to the called method.    //方法参数
options            SendMessageOptions                     Should an error be raised if the method doesn't exist on the target object?  //如果方法不存在 
                                                                          是否生成错误信息  dontRequireReceiver不生成错误信息,RequireReceiver 生成错误信息
4、三者区别
项目层次:Camera,Panel,Btn,label,sprite 这五个对象都附加上了脚本,脚本代码分别如下:
Camera:
void Say(string name) {
        Debug.Log("camera " + name);
    }
Panel:
void Say(string name) {
        Debug.Log("panel " + name);
    }
label:
 void Say(string name) {
        Debug.Log("label " + name);
    }
sprite:
void Say(string name) {
        Debug.Log("sprite " + name);
    }
Btn:
    void Say(string name) {
        Debug.Log("btn " + name);
    }
1、如果btn按钮的OnClick事件代码用的是SendMessage:
void OnClick() {
        this.gameObject.SendMessage("Say", "zwh", SendMessageOptions.DontRequireReceiver);
    }
那么执行结果为:
2、如果btn按钮的OnClick事件代码用的是SendMessageUpwards:
void OnClick() {
        this.gameObject.SendMessageUpwards("Say", "zwh", SendMessageOptions.DontRequireReceiver);
    }
那么执行结果为:
3、如果btn按钮的OnClick事件代码用的是BroadcastMessage:
void OnClick() {
        this.gameObject.BroadcastMessage("Say", "zwh", SendMessageOptions.DontRequireReceiver);
    }
那么执行结果为:

4、总结

SendMessage 查找的方法是在自身当中去查找

SendMessageUpwards 查找的方法是在自身和父类中去查找,如果父类还有父类,继续查找,直到找到根节点为止

BroadcastMessage 查找的方法是在自身和子类中去查找,如果子类还有子类,继续查找,直到没有任何子类

5、多个对象执行同一个方法

NGUITools类里面有一个重载的静态方法:Broadcast (代码如下),这个静态方法的作用就是遍历所有的对象,找到要执行的方法,然后执行对象的SendMessage方法!但是这个方法的效率不高,FindObjectsOfType这个方法肯定耗时间,因为我们项目中的对象肯定很多,这无疑是浪费时间,for循环更是耗时间,再说有可能遍历到没有此方法的对象,做无用功!我们最好的办法就是只执行那些我们需要的某些对象去执行某一方法,而不是遍历所有对象,却不管他有没有此方法,所以我们得寻求好的解决方法,请转到 6

     static public void Broadcast (string funcName)
{
GameObject[] gos = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
for (int i = , imax = gos.Length; i < imax; ++i) gos[i].SendMessage(funcName, SendMessageOptions.DontRequireReceiver);
} /// <summary>
/// Call the specified function on all objects in the scene.
/// </summary> static public void Broadcast (string funcName, object param)
{
GameObject[] gos = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
for (int i = , imax = gos.Length; i < imax; ++i) gos[i].SendMessage(funcName, param, SendMessageOptions.DontRequireReceiver);
}
6、多个对象执行同一个方法优化
这个代码主要意思就是把所有需要执行的对象加到一个集合中,然后遍历此集合执行他们的方法,我想大家都能看懂,我就不详细解释了

 public class NotificationCenter : MonoBehaviour {

     static Hashtable notifications = new Hashtable();

     /// <summary>
/// 增加对象
/// </summary>
/// <param name="gameobject">对象</param>
/// <param name="methodname">方法名</param>
/// <param name="param">参数</param>
public static void AddGameObject(GameObject gameobject, String methodname, object param) {
if (string.IsNullOrEmpty(methodname)) {
Debug.Log("方法名为空");
return;
}
if (!notifications.ContainsKey(methodname)) {
Notification notification = new Notification(gameobject, param);
List<Notification> list = new List<Notification>();
list.Add(notification);
notifications[methodname] = list;
} else {
List<Notification> notifyList = (List<Notification>)notifications[methodname];
if (notifyList.Find(a => a.gameobject == gameobject) == null) {
Notification notification = new Notification(gameobject, param);
notifyList.Add(notification);
notifications[methodname] = notifyList;
}
}
}
/// <summary>
/// 移除对象
/// </summary>
/// <param name="gameobject">对象</param>
/// <param name="methodname">方法名</param>
public static void RemoveGameObject(GameObject gameobject, String methodname) {
if (string.IsNullOrEmpty(methodname)) {
Debug.Log("方法名为空");
return;
}
List<Notification> notifyList = (List<Notification>)notifications[methodname];
if (notifyList != null) {
if (notifyList.Find(a => a.gameobject == gameobject) != null) {
notifyList.RemoveAll(a => a.gameobject == gameobject);
notifications[methodname] = notifyList;
}
if (notifyList.Count == ) {
notifications.Remove(methodname);
}
}
}
/// <summary>
/// 执行方法
/// </summary>
/// <param name="methodName">要执行的方法名称</param>
public static void ExecuteMethod(string methodName) {
if (string.IsNullOrEmpty(methodName)) {
Debug.Log("方法名为空");
return;
}
List<Notification> notifyList = (List<Notification>)notifications[methodName];
if (notifyList == null) {
Debug.Log("对象不存在");
return;
}
foreach (Notification notification in notifyList) {
notification.gameobject.SendMessage(methodName, notification.param, SendMessageOptions.DontRequireReceiver);
}
}
public class Notification {
public GameObject gameobject;
public object param;
public Notification(GameObject gameobject, object param) {
this.gameobject = gameobject;
this.param = param;
}
}
}
7、多个对象同时执行他们的方法
6有几个缺点:使用sendmessage,而sendmessage是利用反射原理实现的,我们知道使用反射在某些情况下效率是不高的,我们最好尽量避免使用反射,而且6传的参数只能为一个,是因为sendmessage的缘故,他只允许传一个参数,可扩展性不好!这里我们使用委托来解决这些问题,代码如下,代码也很简单,我也就不说了,如有问题,可以留言。
 public class delegateNotificationCenter : MonoBehaviour {

     static Hashtable notifications = new Hashtable();

     public delegate void MyFunc(object[] obj);
/// <summary>
/// 增加对象
/// </summary>
/// <param name="gameobject"></param>
/// <param name="methodname"></param>
/// <param name="param"></param>
public static void AddGameObject(GameObject gameobject, String flag, MyFunc func, object[] param) {
if (string.IsNullOrEmpty(flag)) {
Debug.Log("不存在");
return;
}
if (!notifications.ContainsKey(flag)) {
Notification notification = new Notification(gameobject, func, param);
List<Notification> list = new List<Notification>();
list.Add(notification);
notifications[flag] = list;
} else {
List<Notification> notifyList = (List<Notification>)notifications[flag];
if (notifyList.Find(a => a.gameobject == gameobject) == null) {
Notification notification = new Notification(gameobject, func, param);
notifyList.Add(notification);
notifications[flag] = notifyList;
}
}
}
/// <summary>
/// 移除对象
/// </summary>
/// <param name="gameobject"></param>
/// <param name="flag"></param>
public static void RemoveGameObject(GameObject gameobject, String flag) {
if (string.IsNullOrEmpty(flag)) {
Debug.Log("不存在");
return;
}
List<Notification> notifyList = (List<Notification>)notifications[flag];
if (notifyList != null) {
if (notifyList.Find(a => a.gameobject == gameobject) != null) {
notifyList.RemoveAll(a => a.gameobject == gameobject);
notifications[flag] = notifyList;
}
if (notifyList.Count == ) {
notifications.Remove(flag);
}
}
}
/// <summary>
/// 执行方法
/// </summary>
/// <param name="flag"></param>
public static void ExecuteMethod(string flag) {
if (string.IsNullOrEmpty(flag)) {
Debug.Log("不存在");
return;
}
List<Notification> notifyList = (List<Notification>)notifications[flag];
if (notifyList == null) {
Debug.Log("对象不存在");
return;
}
foreach (Notification notification in notifyList) {
notification.func(notification.param);
}
}
public class Notification {
public GameObject gameobject;
public MyFunc func;
public object[] param;
public Notification(GameObject gameobject, MyFunc func, object[] param) {
this.gameobject = gameobject;
this.func = func;
this.param = param;
}
}
}

以上是个人的总结,如有不当,希望大家多多批评指正!

 

最新文章

  1. 【CTO讲堂】以API为核心的移动应用云大发展时代
  2. 解决: is not found. Have you run APT to generate them?
  3. JavaScript DES 加密tripledes.js:
  4. Gradle里配置jetty实现静态资源的热部署
  5. iOS开发-pod install 出错 The dependency `AFNetworking (~&gt; 2.6.0)` is not used in any concrete target.
  6. jQuery事件绑定on、off 和one,取代bind, live, delegate
  7. 易企秀 we+ Maka 兔展 四大H5页面制作工具
  8. springMVC学习笔记三
  9. oracle REGEXP_SUBSTR实现字符串转列
  10. 硬盘被误格式化或Ghost还原后的数据恢复
  11. Web前端-Vue.js必备框架(五)
  12. js 去掉数组对象中的重复对象
  13. java.lang.ClassNotFoundException: javax.servlet.SessionCookieConfig
  14. python 一些方法的时间测试
  15. CentOS+Nginx+Supervisor部署ASP.NET Core项目
  16. Golang--Hello World
  17. Java 注释规范
  18. OpenLayers中的球面墨卡托投影
  19. [转]什么是C++虚函数、虚函数的作用和使用方法
  20. C#在.NET编译执行过程

热门文章

  1. PHP编译安装时常见错误及解决办法,大全
  2. 【转】Android的setTag
  3. RHEL/CentOS 6.x使用EPEL6与remi的yum源安装MySQL 5.5.x
  4. 【转】Spring 整合 Quartz 实现动态定时任务
  5. 深入理解HDFS的架构和原理
  6. zen-Coding在Notepad++中的使用
  7. C# 变量与常量
  8. 一篇SSM框架整合友好的文章(一)
  9. html和node.js实现websocket
  10. 在线代码编辑器 Codemirror 的轻量级 React 组件