———————–转载请注明出处—————————
身为程序小白的我,专业术语不达标,语文能力有限,只能简单粗暴的写下这篇文档。有不同观点或不对的地方请指出。
Unity 3D SendMessage、SendMessageUpwards、BroadcastMessage的使用其实可以在官方API中查到,但官方的总给我们感觉差点什么。这时候就需要我们动手去验证自己的疑虑了。
Message相关有3条指令:
SendMessage:推送消息给自身
SendMessageUpwards:推送消息给自身以及所有的父级对象
BroadcastMessage:推送消息给自身以及所有的子级对象
需要注意的是:
默认是所在脚本所挂的对象为自身,也可以其他对象调用。
消息传递只会直上直下,不会传递给某父(子或自身)级的同级。
参数(调用对象的函数名,可选参数,可选的设置参数)
私有/共有函数都可调用。
网上看到有大牛说可以跨语言使用,我还没试,有兴趣的可以试下。
下面是验证的脚本及结果。建议自己试试,反正不会怀孕。
public class UISprit : MonoBehaviour
{
public GameObject otherObj;
void OnGUI()
{
if(GUI.Button(new Rect(0,0,100,50),"SendMessage "))
{
SendMessage("test01","SendMessage");
}
if(GUI.Button(new Rect(0,60,100,50),"SendMessageUpwards "))
{
SendMessageUpwards("test01","SendMessageUpwards");
}
if(GUI.Button(new Rect(0,120,100,50),"BroadcastMessage "))
{
BroadcastMessage("test01","BroadcastMessage");
}
if(GUI.Button(new Rect(0,180,100,50),"other"))
{
otherObj.SendMessage("test01","otherSendMessage");
otherObj.SendMessageUpwards("test01","otherSendMessageUpwards");
otherObj.BroadcastMessage("test01","otherBroadcastMessage");
}
}
}
public class Test : MonoBehaviour
{
void test01(string str)
{
Debug.Log( this.gameObject.name + "****" +str );
}
public void Test02(string str)
{
Debug.Log( this.gameObject.name + "****" + str );
}
}