unity 中的 SendMessage

GameObject.SendMessage 发送消息

function SendMessage (methodName : string, value : object = null, options : SendMessageOptions = SendMessageOptions.RequireReceiver) : void

向同级发送消息。

这个游戏物体上的所有MonoBehaviour上调用名称为methodName的方法。

接收消息的方法可以通过不要参数的方法来选择忽略参数。当选项被设置为SendMessageOptions.RequireReceiver时,如果消息没有被任何一个组件处理,则会打印一个错误。

GameObject.SendMessageUpwards 向上发送消息

function SendMessageUpwards (methodName : string, value : object = null, options : SendMessageOptions = SendMessageOptions.RequireReceiver) : void

向物体和父物体发送消息

这个游戏物体及其祖先物体的所有MonoBehaviour中调用名称为methodName的方法。

会调用到最顶层的父亲物体,不仅是当前父物体,只要是层级比他高的都会调用)

接收消息的方法可以通过不要参数的方法来选择忽略参数.当选项被设置为SendMessageOptions.RequireReceiver时,如果消息没有被任何一个组件处理,则会打印一个错误。

Component.BroadcastMessage 广播消息

function BroadcastMessage (methodName : string, parameter : object = null, options : SendMessageOptions =SendMessageOptions.RequireReceiver) : void

在游戏物体每一个MonoBehaviour和它的全部子物体上调用名为methodName的方法。

通俗的解释:

BroadcastMessage朝物体和所有子物体发送消息。

也就

对一个物体及其所有子物体,进行消息的广播,如果其中任何子物体上贴有脚本,而脚本中有相应的处理此消息的函数,则Invoke调用之。

The receiving method can choose to ignore parameter by having zero arguments. if options is set to SendMessageOptions.RequireReceiver an error is printed when the message is not picked up by any component.

接受消息的此方法(函数)可以通过设置没有引用参数表来忽略传过来的消息中的参数。如果选项Option中设置成了SendMessageOptions.RequireReceiver,那么当没有任何脚本组件接受此消息时,一个相应的错误会弹出来


实际上这个函数的目的就是为了调用其他脚本中的函数,也就是交互目的他会在指定的gameobject上所依附的脚本中针对函数名"string"去检索. 找到后调用并传送参数object.(参数可以为空)

简单测试:

using UnityEngine;

using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
public static NewBehaviourScript ins;
public GameObject go;
// Use this for initialization
void Start () {
ins = this;
go.SendMessageUpwards ("A", 1);
}

// Update is called once per frame
void Update () {

}

}

using UnityEngine;
using System.Collections;


public class C : MonoBehaviour {

public int c;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}
public void A(int i){

c = i;
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值