unity中消息传递的三种方法

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包含该消息,也不会执行~)



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值