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


    为了方便多个物体间的消息传达与接收,Unity中包含了几种消息推送机制 :

    分别为SendMessage、SendMessageUpwards、BroadcastMessage。

    我们首先以SendMessage为例:

    public void SendMessage(string methodName,object value,SendMessageOptions options);

    可以看到它有三个参数,分别为“被调用目标方法的方法名”、“传递给目标方法的参数”、“当目标方法不存在时,是否告知开发者(是否打印错误)”

    下面我们制作简单的项目Demo测试:

    新建场景并设置以下4个物体的层级关系如图,其中Parent物体挂载“test1”和“test2”脚本,Grandparent 和 Child 以及 Other挂载“test2”脚本

     test1 和 test2脚本:(test1脚本包括消息发送和接收方法,test2脚本仅包括消息接收方法)

    using UnityEngine;
    public class test1 : MonoBehaviour {
        void Update()
        {
            if (Input.GetMouseButtonDown(0))//点击鼠标左键执行以下操作 
            {
                SendMessage("Example1", 123, SendMessageOptions.DontRequireReceiver);//尝试调用“Example1”方法
            }
        }
        void Example1(int i)
        {
             Debug.Log(name+"  :test1  :"+ i);
        }
    }
    using UnityEngine;
    public class test2 : MonoBehaviour {
        void Example1(int i)
        {
             Debug.Log(name+"  :test2  :"+ i);
        }
    }

    运行程序并点击鼠标左键,得到输出结果如下 :(挂载test1的“Parent”物体接收到)

     可以得出结论:SendMessage的消息传递机制,仅对当前对象(自身)所挂载的所有脚本发送消息有效,对父物体及其子物体无效,对其他物体无效。

    同样的,我们分别编写代码对SendMessageUpwards、BroadcastMessage进行测试,

    根据输出结果,可分别得出结论:

    SendMessageUpwards的消息传递机制,对当前对象(自身)及它的父物体所挂载的所有脚本发送消息有效,对其子物体无效,对其他物体无效。

    BroadcastMessage的消息传递机制,与SendMessageUpwards正好相反,对当前对象(自身)及它的子物体所挂载的所有脚本发送消息有效,对其父物体无效,对其他物体无效。

  • 相关阅读:
    Ubuntu10.04搭建linux-0.11编译环境(1.bochs安装和使用)
    Linux 0.11内核编译和bochs上的实验环境的搭建
    64位Linux的内核和用户地址空间
    2012年计算机考研大纲——操作系统
    【27.34%】【codeforces 611D】New Year and Ancient Prophecy
    【14.94%】【codeforces 611E】New Year and Three Musketeers
    【53.57%】【codeforces 610C】Harmony Analysis
    【42.49%】【hdu 1542】Atlantis(线段树扫描线简析)
    【49.23%】【hdu 1828】Picture
    【20.51%】【codeforces 610D】Vika and Segments
  • 原文地址:https://www.cnblogs.com/Feiyuzhu/p/12090655.html
Copyright © 2020-2023  润新知