每一个对象都有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;
}
}
}

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

 

Unity-SendMessage的更多相关文章

  1. Unity SendMessage方法

    我们今天研究下SendMessage方法, 如果我们需要执行某一个组件的方法时候可以使用SendMessage gameObject.SendMessage("A"); 即可通知当 ...

  2. Unity 发布的 WebGL 使用SendMessage传递多个参数

    如果要实现Unity与浏览器的数据交互一般都会采用两种方式 方法一: Application.ExternalCall("SayHello","helloworld&qu ...

  3. Unity 发布的 WenGL 使用SendMessage传递多个参数

    如果要实现Unity与浏览器的数据交互一般都会采用两种方式 方法一: Application.ExternalCall("SayHello","helloworld&qu ...

  4. Unity的3种消息传递方法(SendMessage等)

    为了方便多个物体间的消息传达与接收,Unity中包含了几种消息推送机制 : 分别为SendMessage.SendMessageUpwards.BroadcastMessage. 我们首先以SendM ...

  5. Unity中SendMessage和Delegate效率比较

    网上直接搜的代码.需要的使用也简单,所以就不过多说明. 但是网上都说,他们之间的差距,delegate比较快,效果高.怎么个高法呢?还是自己来测试下时间. 故此, 个人之用来比较下时间差别. 一.直接 ...

  6. Unity的sendmessage用法

    刚学完sendmessage用法,自己也尝试测试了一下,用法如下: 1.在unity2017新建一个场景test 2.在场景中添加一个立方体cube作为主角,另添加一个胶囊体capsule,调整为如图 ...

  7. Unity的SendMessage方法

    用法(该对象所有脚本都能收到): gameObject.SendMessage("要执行的方法名"); 通知的另一种实现: gameObject.GetComponent<脚 ...

  8. 【Unity系统知识】关于SendMessage的用法

    [Message相关有3个函数] 一.功能:用于向某个GameObject发送一条信息,让它完成特定功能. 1.执行GameObject自身的Script中“函数名”的函数SendMessage (& ...

  9. Unity插件之plyGame教程:DiaQ对话系统

    本文为孤月蓝风编写,转载请注明出处:http://fengyu.name/?cat=game&id=296 DiaQ是plyGame旗下的一款对话及任务系统.拥有可视化的对话及任务编辑器,能够 ...

  10. Unity 最佳实践

    转帖:http://www.glenstevens.ca/unity3d-best-practices/ 另外可以参考:http://devmag.org.za/2012/07/12/50-tips- ...

随机推荐

  1. python 爬糗事百科

    糗事百科网站段子爬取,糗事百科是我见过的最简单的网站了!!! #-*-coding:utf8-*- import requests import re import sys reload(sys) s ...

  2. 导航栏上的item的位置设置

    /** leftItem */ UIButton *leftbtn = [[UIButton alloc]initWithFrame:CGRectMake(, , , )]; [leftbtn set ...

  3. 用js给元素加css

    1.如果是没有CSS文件,或者要修改的不在CSS文件里,那么: document.getElementById('DIV标签的ID').style.属性='属性值'; 这样就可以了.2.如果,样式是写 ...

  4. 14、SpringBoot------定制错误返回内容json格式

    开发工具:STS 前言: 在前后端分离的项目中,当前端向后端请求资源失败时,想知道具体的错误原因,给用户予以提示. 但是,在springboot中返回内容是固定的.并不适合我们前端进行分析. 所以,就 ...

  5. mongodb基础环境部署(windows系统下)

    Normal 0 false 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE /* Style Definitions */ table.MsoNorma ...

  6. 表单验证实现React-router跳转

    方法一:broserHistory.push handleSubmit(e){ e.preventDefault(); const path = '/demo'; broserHistory.push ...

  7. activemq启动闪退/失败 (Illegal character in hostname at index 5: ws://****:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600)

    java.net.URISyntaxException: Illegal character in hostname at index 5: ws://****:61614?maximumConnec ...

  8. gd库 给底图写入文字问题

    png-8的图片 设置颜色会返回false,换成png-24的就可以了

  9. ajaxfileupload多文件上传 - 修复只支持单个文件上传的bug

    搜索: jquery ajaxFileUpload AjaxFileUpload同时上传多个文件 原生的AjaxFileUpload插件是不支持多文件上传的,通过修改AjaxFileUpload少量代 ...

  10. 关于IT术语---ip、uv、pv、tps、qps、rps

    涉及到IT方面的几条术语,这里要好好说道说道: 只要和网站打交道,难免会经常听到一系列的转有名词  >>>  系统今日UV多少.PV多少.QPS多少之类的问题.这里就对这些常见的术语 ...