unity中消息传递的三种方法

来源:互联网 发布:qq飞车cdkey软件 编辑:程序博客网 时间:2024/05/21 07:58

unity中提供了对象间消息传递的三种方法:

  1. BroadcastMessage()方法
  2. SendMessage()方法
  3. 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包含该消息,也不会执行~)



0 0