官方文档>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发送给当前作用域内的接收方(也就是谁发送的,就会给自个儿发一份消息)。