Unity three kinds of messaging method (like the SendMessage)

In order to facilitate the received message communicated between the plurality of objects, Unity push message contains several mechanisms:

分别为SendMessage、SendMessageUpwards、BroadcastMessage。

We begin with SendMessage example:

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

It can be seen that there are three parameters, namely the "target method is called the method name", "arguments passed to the target method," and "when the target method does not exist, whether to inform the developer (whether to print the error)."

Let's create a simple test project Demo:

New scene objects and set the following four hierarchical relationship is shown, wherein the object mount Parent "test1" and "test2" scripts, and Child and Other Grandparent mount "test2" Script

 test1 and test2 script: (test1 script send messages and receive method comprising, receiving message only comprises test2 script Method)

a using UnityEngine;
 public  class test1: MonoBehaviour {
     void Update () 
    { 
        IF (Input.GetMouseButtonDown ( 0 )) // click the left mouse button to do the following 
        { 
            SendMessage ( " Example1 " , 123 , SendMessageOptions.DontRequireReceiver); // try to call "Example1" method 
        } 
    } 
    void Example1 ( int I) 
    { 
         Debug.Log (name + ": test1:" + I); 
    } 
}
using UnityEngine;
public class test2 : MonoBehaviour {
    void Example1(int i)
    {
         Debug.Log(name+"  :test2  :"+ i);
    }
}

Run the program and click the left mouse button to obtain the following output :( mount "Parent" object received test1)

 

 It can be concluded: SendMessage message passing mechanism, only the current object (itself) all scripts are mounted to send a message is valid, the parent object and child objects invalid, ineffective against other objects.

 

Similarly, we are writing code for SendMessageUpwards, BroadcastMessage test

The output result, conclusions can be drawn are:

SendMessageUpwards message passing, and all of its parent objects to the script mount effective to send a message to the current object (itself), its sub-objects invalid, ineffective against other objects.

BroadcastMessage message passing, and SendMessageUpwards contrary, and all its sub-scripts mounted Objects send messages valid for the current object (itself), invalid parent object, other objects invalid.

Guess you like

Origin www.cnblogs.com/Feiyuzhu/p/12090655.html