赞
踩
以下有关SendMessage的发送消息的方法,都需要继承 MonoBehaviour,属于Mono封装的方法。
1、SendMessage(); 只发送给悬挂在当前方法所悬挂的游戏物体上的脚本
SendMessage(string methodName); (方法名)
SendMessage(string methodName, object value); ( 方法名,传参)
SendMessage(string methodName, SendMessageOptions options);(方法名,如果找不到要调用的方法,是否引发错误)=》第二个参数解析:
① SendMessageOptions.DontRequireReceiver,不引发报错。
②SendMessageOptions.RequireReceiver,引发报错。
SendMessage(string methodName, object value, SendMessageOptions options);(方法名,参数,查找不到方法是否引发报错)
2、SendMessageUpwards(); 发送给本身和其所有父物体,参数类型同1
3、BroadcastMessage();发送给本身和其所有子物体,参数类型同1
与委托调用速度的比较,调用50000次的结果,SendMessage比委托慢10倍(很久以前看的一篇文章的测试方法,具体在哪找不到了)。代码如下 :
public delegate void MyDelegate(string arg1);
public MyDelegate myDelegate;
bool isStart;
float timeStart;
int count;
bool isStartSendMessage;
void Start()
{
myDelegate += myFunciton1;
}
void Update()
{
if (isStart)
{
isStart = false;
count = 0;
timeStart = Time.realtimeSinceStartup;
Debug.Log("Start = " + timeStart);
for (int i = 0; i < 50000; i++)
{
if (myDelegate != null) myDelegate("");
}
}
if (isStartSendMessage)
{
isStartSendMessage = false;
count = 0;
timeStart = Time.realtimeSinceStartup;
Debug.Log("Start = " + timeStart);
for (int i = 0; i < 50000; i++)
{
this.gameObject.SendMessage("myFunciton1", "", SendMessageOptions.DontRequireReceiver);
}
}
}
void OnGUI()
{
if (GUILayout.Button("INVOKE Delegate"))
{
isStart = true;
}
if (GUILayout.Button("SendMessage"))
{
isStartSendMessage = true;
}
}
void myFunciton1(string s)
{
count++;
if (count == 50000)
{
Debug.Log("End = " + Time.realtimeSinceStartup);
Debug.Log("Time Spent = " + (Time.realtimeSinceStartup - timeStart));
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。