Unity中GameObject发送消息

本篇文档为转载内容,感谢csdn上的博客资源

本文仅供学习、笔记 、作为备忘左右

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

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

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


方法类型

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 () {
    
    }
}

看到打印出来的效果就可以了




你可能感兴趣的:(Unity)