【unity学习笔记二十一】SendMessage 消息的推送

GameObject类有三个方法可以实现发送消息,即SendMessage、BroadcastMessage和SendMessageUpwards。但是它们之间也是有区别的,如下:

假如cube0是cube1和Sphere0的父类一级,而Sphere1和Sphere2处于同一级。

  • SendMessage只能向自身发送消息,和自身同级的物体不会接收到消息。Sphere1不能接收到Sphere2发送的消息。
  • BroadcastMessage是向自身以及所有子类发送消息,和自身同级的物体不会收到消息。Sphere0、Sphere1和Sphere2可以接收Sphere0发送的消息。
  • SendMessageUpwards向自身和其所有父类发送消息。和自身同级的物体不能接收到消息。Sphere0可以接收到Sphere1和Sphere2发送的消息,但是Sphere1和Sphere2不能接收到彼此发送的消息。

方法类型

SendMessage、BroadcastMessage、SendMessageUpwards三种方法具有同样的重载方法

public void SendMessage(string methodName);
public void SendMessage(string methodName,object value);
public void SendMessage(string methodName,SendMessageOptions options);
public void SendMessage(string methodName,object value,SendMessageOptions options);


演示

using UnityEngine;
using System.Collections;

public class BroadMessage_ts : MonoBehaviour {

// Use this for initialization
void Start () {

gameObject.BroadcastMessage(“GetParentMessage”,gameObject.name+”:use BroadcastMessage send!”);
}

public void GetParentMessage(string str)
{
Debug.Log(gameObject.name + “收到父类发送的消息: ” + str);
}

public void GetChildrenMessage(string str)
{
Debug.Log(gameObject.name + “收到子类发送的消息: ” + str);
}

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

}
}

 

using UnityEngine;
using System.Collections;

public class SendMessage_ts : MonoBehaviour {

// Use this for initialization
void Start () {

gameObject.SendMessage(“GetSelfMessage”, gameObject.name + “use SendMessage send!”);
}

public void GetSelfMessage(string str)
{
Debug.Log(gameObject.name + “收到自身发送的消息: ” + str);
}

public void GetParentMessage(string str)
{
Debug.Log(gameObject.name + “收到父类发送的消息: ” + str);
}

public void GetChildrenMessage(string str)
{
Debug.Log(gameObject.name + “收到子类发送的消息: ” + str);
}

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

}
}

 

using UnityEngine;
using System.Collections;

public class SendMessageUpwards_ts : MonoBehaviour {

// Use this for initialization
void Start()
{

gameObject.SendMessageUpwards(“GetChildrenMessage”, gameObject.name + “use SendMessageUpwards send!”);
}

public void GetChildrenMessage(string str)
{
Debug.Log(gameObject.name + “收到子类发送的消息: ” + str);
}

public void GetParentMessage(string str)
{
Debug.Log(gameObject.name + “收到父类发送的消息: ” + str);
}

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

}
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注