Unity3D中的GameObject.发送消息与接收消息

目录

 

概述

SendMessage

原型:

作用:

SendMessageUpwards

原型:

作用:

BroadcastMessage

原型:

作用:


概述

Unity给我们提供了游戏物体(GameObject)之间的通信方法,如下所示:

gameObject.SendMessge(string methodName, object parameter = null, SendMessageOptions options = SendMessageOptions.RequireReceiver));
gameObject.SendMessageUpwards(string methodName, object parameter = null, SendMessageOptions options = SendMessageOptions.RequireReceiver));
gameObject.BroadcastMessage(string methodName, object parameter = null, SendMessageOptions options = SendMessageOptions.RequireReceiver));

调用游戏物体的上述方法就可以对游戏物体发送消息,这个消息会被游戏物体身上的全部脚本或者父物体、子物体身上的全部脚本接收,并会接收到一个为object类型的参数。

这个东西的原理Unity用的是反射机制实现的。这个消息推送机制可以说是方便了脚本开发,它实现的是一种伪监听者模式。

SendMessage

原型:

public void SendMessage(string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);

作用:

参数“string methodName”是指:和反射一样,通过方法名查找方法,并调用。

参数“object value”是指:此参数作为传入参数(可选参数)

参数“SendMessageOptions options”是指:发送消息选项(可选参数),其作用如下:

SendMessageOptions.RequireReceiver //如果没有找到相应函数就报错
SendMessageOptions.DontRequireReceiver //如果没有找到相应函数不报错并自动忽略


SendMessageUpwards

原型:

public void SendMessageUpwards(string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);

作用:

它的作用和SendMessage类似,如上所示。

不同的是“发送消息向上”,(遍历所有父对象:父物体的父物体等身上所有脚本)。

BroadcastMessage

原型:

public void BroadcastMessage(string methodName, object parameter = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);

作用:

它的作用和SendMessage类似,如上所示。

不同的是“广播消息”,(遍历所有的子对象:子物体的子物体等身上所有脚本)。

猜你喜欢

转载自blog.csdn.net/m0_46419510/article/details/110679559