• Unity-SendMessage


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

     1     static public void Broadcast (string funcName)
     2     {
     3         GameObject[] gos = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
     4         for (int i = 0, imax = gos.Length; i < imax; ++i) gos[i].SendMessage(funcName, SendMessageOptions.DontRequireReceiver);
     5     }
     6 
     7     /// <summary>
     8     /// Call the specified function on all objects in the scene.
     9     /// </summary>
    10 
    11     static public void Broadcast (string funcName, object param)
    12     {
    13         GameObject[] gos = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
    14         for (int i = 0, imax = gos.Length; i < imax; ++i) gos[i].SendMessage(funcName, param, SendMessageOptions.DontRequireReceiver);
    15     }
    6、多个对象执行同一个方法优化
    这个代码主要意思就是把所有需要执行的对象加到一个集合中,然后遍历此集合执行他们的方法,我想大家都能看懂,我就不详细解释了
     1 public class NotificationCenter : MonoBehaviour {
     2 
     3     static Hashtable notifications = new Hashtable();
     4 
     5     /// <summary>
     6     /// 增加对象
     7     /// </summary>
     8     /// <param name="gameobject">对象</param>
     9     /// <param name="methodname">方法名</param>
    10     /// <param name="param">参数</param>
    11     public static void AddGameObject(GameObject gameobject, String methodname, object param) {
    12         if (string.IsNullOrEmpty(methodname)) {
    13             Debug.Log("方法名为空");
    14             return;
    15         }
    16         if (!notifications.ContainsKey(methodname)) {
    17             Notification notification = new Notification(gameobject, param);
    18             List<Notification> list = new List<Notification>();
    19             list.Add(notification);
    20             notifications[methodname] = list;
    21         } else {
    22             List<Notification> notifyList = (List<Notification>)notifications[methodname];
    23             if (notifyList.Find(a => a.gameobject == gameobject) == null) {
    24                 Notification notification = new Notification(gameobject, param);
    25                 notifyList.Add(notification);
    26                 notifications[methodname] = notifyList;
    27             }
    28         }
    29     }
    30     /// <summary>
    31     /// 移除对象
    32     /// </summary>
    33     /// <param name="gameobject">对象</param>
    34     /// <param name="methodname">方法名</param>
    35     public static void RemoveGameObject(GameObject gameobject, String methodname) {
    36         if (string.IsNullOrEmpty(methodname)) {
    37             Debug.Log("方法名为空");
    38             return;
    39         }
    40         List<Notification> notifyList = (List<Notification>)notifications[methodname];
    41         if (notifyList != null) {
    42             if (notifyList.Find(a => a.gameobject == gameobject) != null) {
    43                 notifyList.RemoveAll(a => a.gameobject == gameobject);
    44                 notifications[methodname] = notifyList;
    45             }
    46             if (notifyList.Count == 0) {
    47                 notifications.Remove(methodname);
    48             }
    49         }
    50     }
    51     /// <summary>
    52     /// 执行方法
    53     /// </summary>
    54     /// <param name="methodName">要执行的方法名称</param>
    55     public static void ExecuteMethod(string methodName) {
    56         if (string.IsNullOrEmpty(methodName)) {
    57             Debug.Log("方法名为空");
    58             return;
    59         }
    60         List<Notification> notifyList = (List<Notification>)notifications[methodName];
    61         if (notifyList == null) {
    62             Debug.Log("对象不存在");
    63             return;
    64         }
    65         foreach (Notification notification in notifyList) {
    66             notification.gameobject.SendMessage(methodName, notification.param, SendMessageOptions.DontRequireReceiver);
    67         }
    68     }
    69     public class Notification {
    70         public GameObject gameobject;
    71         public object param;
    72         public Notification(GameObject gameobject, object param) {
    73             this.gameobject = gameobject;
    74             this.param = param;
    75         }
    76     }
    77 }
    7、多个对象同时执行他们的方法
    6有几个缺点:使用sendmessage,而sendmessage是利用反射原理实现的,我们知道使用反射在某些情况下效率是不高的,我们最好尽量避免使用反射,而且6传的参数只能为一个,是因为sendmessage的缘故,他只允许传一个参数,可扩展性不好!这里我们使用委托来解决这些问题,代码如下,代码也很简单,我也就不说了,如有问题,可以留言。
     1 public class delegateNotificationCenter : MonoBehaviour {
     2 
     3     static Hashtable notifications = new Hashtable();
     4 
     5     public delegate void MyFunc(object[] obj);
     6     /// <summary>
     7     /// 增加对象
     8     /// </summary>
     9     /// <param name="gameobject"></param>
    10     /// <param name="methodname"></param>
    11     /// <param name="param"></param>
    12     public static void AddGameObject(GameObject gameobject, String flag, MyFunc func, object[] param) {
    13         if (string.IsNullOrEmpty(flag)) {
    14             Debug.Log("不存在");
    15             return;
    16         }
    17         if (!notifications.ContainsKey(flag)) {
    18             Notification notification = new Notification(gameobject, func, param);
    19             List<Notification> list = new List<Notification>();
    20             list.Add(notification);
    21             notifications[flag] = list;
    22         } else {
    23             List<Notification> notifyList = (List<Notification>)notifications[flag];
    24             if (notifyList.Find(a => a.gameobject == gameobject) == null) {
    25                 Notification notification = new Notification(gameobject, func, param);
    26                 notifyList.Add(notification);
    27                 notifications[flag] = notifyList;
    28             }
    29         }
    30     }
    31     /// <summary>
    32     /// 移除对象
    33     /// </summary>
    34     /// <param name="gameobject"></param>
    35     /// <param name="flag"></param>
    36     public static void RemoveGameObject(GameObject gameobject, String flag) {
    37         if (string.IsNullOrEmpty(flag)) {
    38             Debug.Log("不存在");
    39             return;
    40         }
    41         List<Notification> notifyList = (List<Notification>)notifications[flag];
    42         if (notifyList != null) {
    43             if (notifyList.Find(a => a.gameobject == gameobject) != null) {
    44                 notifyList.RemoveAll(a => a.gameobject == gameobject);
    45                 notifications[flag] = notifyList;
    46             }
    47             if (notifyList.Count == 0) {
    48                 notifications.Remove(flag);
    49             }
    50         }
    51     }
    52     /// <summary>
    53     /// 执行方法
    54     /// </summary>
    55     /// <param name="flag"></param>
    56     public static void ExecuteMethod(string flag) {
    57         if (string.IsNullOrEmpty(flag)) {
    58             Debug.Log("不存在");
    59             return;
    60         }
    61         List<Notification> notifyList = (List<Notification>)notifications[flag];
    62         if (notifyList == null) {
    63             Debug.Log("对象不存在");
    64             return;
    65         }
    66         foreach (Notification notification in notifyList) {
    67             notification.func(notification.param);
    68         }
    69     }
    70     public class Notification {
    71         public GameObject gameobject;
    72         public MyFunc func;
    73         public object[] param;
    74         public Notification(GameObject gameobject, MyFunc func, object[] param) {
    75             this.gameobject = gameobject;
    76             this.func = func;
    77             this.param = param;
    78         }
    79     }
    80 }

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

     
  • 相关阅读:
    PE文件捆绑实现二:(远程线程注入)
    C++中Vector清空
    ttrss更新到最新版本后发访问非80和443端口规避
    Git配置https_proxy访问github失败
    Haproxy配置拦截指定src的连接
    synology git管理程序添加
    ActiveMQ深入浅出系列 (一)
    sl4fj日志级别
    HTTP上传文件解析
    linux下jcmd无法获取jvmdump
  • 原文地址:https://www.cnblogs.com/MrZivChu/p/sendmessage.html
Copyright © 2020-2023  润新知