Unity 3D SendMessage、SendMessageUpwards、BroadcastMessage使用

———————–转载请注明出处—————————

身为程序小白的我,专业术语不达标,语文能力有限,只能简单粗暴的写下这篇文档。有不同观点或不对的地方请指出。

Unity 3D SendMessage、SendMessageUpwards、BroadcastMessage的使用其实可以在官方API中查到,但官方的总给我们感觉差点什么。这时候就需要我们动手去验证自己的疑虑了。
Message相关有3条指令:
SendMessage:推送消息给自身
SendMessageUpwards:推送消息给自身以及所有的父级对象
BroadcastMessage:推送消息给自身以及所有的子级对象
需要注意的是:

默认是所在脚本所挂的对象为自身,也可以其他对象调用。
消息传递只会直上直下,不会传递给某父(子或自身)级的同级。
参数(调用对象的函数名,可选参数,可选的设置参数)
私有/共有函数都可调用。
网上看到有大牛说可以跨语言使用,我还没试,有兴趣的可以试下。

下面是验证的脚本及结果。建议自己试试,反正不会怀孕。

public class UISprit : MonoBehaviour 
{
    public GameObject otherObj;

    void OnGUI()
    {
        if(GUI.Button(new Rect(0,0,100,50),"SendMessage "))
        {
            SendMessage("test01","SendMessage");
        }

        if(GUI.Button(new Rect(0,60,100,50),"SendMessageUpwards "))
        {
            SendMessageUpwards("test01","SendMessageUpwards");
        }

        if(GUI.Button(new Rect(0,120,100,50),"BroadcastMessage "))
        {
            BroadcastMessage("test01","BroadcastMessage");
        }

        if(GUI.Button(new Rect(0,180,100,50),"other"))
        {
            otherObj.SendMessage("test01","otherSendMessage");
            otherObj.SendMessageUpwards("test01","otherSendMessageUpwards");
            otherObj.BroadcastMessage("test01","otherBroadcastMessage");
        }
    }
}
public class Test : MonoBehaviour 
{
    void test01(string str)
    {
        Debug.Log( this.gameObject.name + "****" +str );
    }

    public void Test02(string str)
    {
        Debug.Log( this.gameObject.name + "****" + str );
    }

}

这里写图片描述
这里写图片描述
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值