Game Development Reference
In-Depth Information
SendMessage and BroadcastMessage
The
MonoBehaviour
class included in the Unity API, which acts as the base class for
most new scripts, offers the
SendMessage
and
BroadcastMessage
methods. Using
these, you can easily execute functions by name on all components attached to an
object. To invoke a method of a class, you typically need a local reference to that
class to access and run its functions as well as to access its variables. However, the
SendMessage
and
BroadcastMessage
functions let you run functions using string
values by simply specifying the name of a function to run. This is very convenient
and makes your code look a lot simpler and shorter at the cost of efficiency, as we'll
see later. Refer to the following code sample 1-16:
01 using UnityEngine;
02 using System.Collections;
03
04 public class MyClass : MonoBehaviour
05 {
06 void start()
07 {
08 //Will invoke MyFunction on ALL components/scripts
attached to this object (where the function is present)
09 SendMessage("MyFunction",
SendMessageOptions.DontRequireReceiver);
10 }
11
12 //Runs when SendMessage is called
13 void MyFunction()
14 {
15 Debug.Log ("hello");
16 }
17 }
The following are the comments for code sample 1-16:
•
Line 09
:
SendMessage
is called to invoke the function
MyFunction
.
MyFunction
will be invoked not only on this class but on all other
components attached to
GameObject
, if they have a
MyFunction
member, including the
Transform
component as well as others.
•
Line 09
: The parameter
SendMessageOptions.DontRequireReceiver
defines what happens if
MyFunction
is not present on a component.
Here, it specifies that Unity should ignore the component and move
on to the next calling
MyFunction
wherever it is found.