unity中提供了对象间消息传递的三种方法:
- BroadcastMessage()方法
- SendMessage()方法
- SendMessageUpwards()方法
BroadcastMessage方法:
void BroadcastMessage (string methodName, object parameter = null, SendMessageOptions options = SendMessageOptions.RequireReceiver)
向该游戏物体及其子物体的所有MonoBehavior发送名字为methodName的消息,其中,parameter为methodName的参数,options决定了发送消息的选项(默认为RequireReceiver,此时如果没有一个组件进行处理就会打印一个错误~)【说是发送消息,实质上是调用MonoBehavior中名称为methodName的函数~,如果接收消息的组件中没有相应名称的函数,就不会执行函数~】
using UnityEngine;
using System.Collections;
public class MessageTest : MonoBehaviour
{
public void ApplyMessage(string name)
{
Debug.Log("The name is :" + name);
}
void Awake()
{
gameObject.BroadcastMessage("ApplyMessage", gameObject.name);
}
}
SendMessage方法:
void SendMessage(string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);
同上,只不过发送对象为该游戏对象的所有MonoBehavior。(父物体、子物体中所有MonoBehavior都不会接收到该消息,即使包含methodName的方法)
SendMessageUpwards方法:
void SendMessageUpwards(string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);
同上,只不过发送对象为该游戏对象及其所有父对象的所有MonoBehavior。(即使子物体中某些Monobehavior包含该消息,也不会执行~)