经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » 游戏设计 » 查看文章
Unity API学习笔记(2)-GameObject的3种Message消息方法
来源:cnblogs  作者:BrainK_1400  时间:2019/7/17 12:49:10  对本文有异议

官方文档>GameObject

首先建立测试对象:

 

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

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

 

  1. 1 using System.Collections;
  2. 2 using System.Collections.Generic;
  3. 3 using UnityEngine;
  4. 4
  5. 5 public class GameObjectTest : MonoBehaviour
  6. 6 {
  7. 7 // Start is called before the first frame update
  8. 8 public GameObject target;
  9. 9 void Start()
  10. 10 {
  11. 11 // target.SendMessage("Hello");
  12. 12 // target.BroadcastMessage("Hello");
  13. 13 // target.SendMessageUpwards("Hello");
  14. 14 }
  15. 15 void Hello()
  16. 16 {
  17. 17 Debug.Log("In GameObjectTest:" + target.name);
  18. 18 }
  19. 19 }
  1. 1 using System.Collections;
  2. 2 using System.Collections.Generic;
  3. 3 using UnityEngine;
  4. 4
  5. 5 public class Target : MonoBehaviour
  6. 6 {
  7. 7 public GameObject target;
  8. 8 void Hello()
  9. 9 {
  10. 10 Debug.Log("In Target:" + target.name);
  11. 11 }
  12. 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发送给当前作用域内的接收方(也就是谁发送的,就会给自个儿发一份消息)。

 

原文链接:http://www.cnblogs.com/braink-1400/p/11200028.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号