Unity API学习笔记(2)-GameObject的3种Message消息方法

官方文档>GameObject

首先建立测试对象:

 

在Father中添加两个脚本(GameObejctTest和Target),分别用来发送Message和接受Message:

在其它GameObject中添加名为Target的脚本。

 

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class GameObjectTest : MonoBehaviour
 6 {
 7     // Start is called before the first frame update
 8     public GameObject target;
 9     void Start()
10     {
11         // target.SendMessage("Hello");
12         // target.BroadcastMessage("Hello");
13         // target.SendMessageUpwards("Hello");
14     }
15     void Hello()
16     {
17         Debug.Log("In GameObjectTest:" + target.name);
18     }
19 }
 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class Target : MonoBehaviour
 6 {
 7     public GameObject target;
 8     void Hello()
 9     {
10         Debug.Log("In Target:" + target.name);
11     }
12 }

分别依次执行:

  •   SendMessage:Calls the method named methodName on every MonoBehaviour in this game object.

      

    也就是当前发送端(Father)所在GameObject下的组件都接收到了Message,但是Son没有接收到,Others没有接收到,Ancestor也没有。

 

  •   BroadcasMessage:Calls the method named methodName on every MonoBehaviour in this game object or any of its children.

    

    这里可以看到所有的子类包括子类的子类都接收到了Message,要说明一点的是,组件(Component)也是属于GameObject的,所以也接收到了Message。

  •   SendMessageUpwards:Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.

    

    它的父类(Ancestor)接收到了消息,包括它本身。(这里说的是每一个父类都可以接收到Message,意思是如果Ancestor上还有类,那么它们都可以接收到Message)

 

通过返回结果不难发现,这三种方法都会调用Message发送给当前作用域内的接收方(也就是谁发送的,就会给自个儿发一份消息)。

 

转载于:https://www.cnblogs.com/braink-1400/p/11200028.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值