Game Development Reference
In-Depth Information
Note
Both the
SendMessage
and the
BroadcastMessage
functions are useful, but can cause
performance overhead when used extensively in frame-based functions, such as
Update
. For this reason,
use them judiciously and in a way that works well with your game. If you find their use to be generally too
costly for your game, then consider implementing an event system using C# interfaces. This subject will be
explored in brief in the final chapter.
SendMessage.
When you want to run a function of a specified name on
all
components of a
single
GameObject, then you'll need the
SendMessage
function.
The declaration for this function is given as follows (also see the Unity online
documentation at
http://docs.unity3d.com/Documentation/
ScriptReference/
Component.SendMessage.html)
:
void SendMessage(
string methodName, SendMessageOptions options
);
An example of its use is as follows:
MyGameObject.SendMessage("Myfunction", SendMessageOptions. DontRequireReceiver);
MethodName
and
Options. MethodName
refers to the function name to execute on
all
components of the specified
game object. The
Options
argument simply specifies what should happen if
a component is encountered that has no function with a matching name to
execute. Options can be either
DontRequireReceiver
or
RequireReceiver.
DontRequireReceiver
means that if a component is found with no matching
function to execute, then that component is simply ignored.
RequireReceiver
means that if no function is found, an exception or error will be invoked
automatically by Unity and will be printed to the console.
BroadcastMessage.
Usually,
SendMessage
is all you need to invoke generic
behavior on a GameObject without knowing the implementation specifics
and interfaces of its components. But sometimes, you'll need more than this.
Specifically, you'll occasionally want to invoke functions and behavior on all
components across
multiple
GameObjects, and not just one object. If you
need multiple objects to simultaneously hide, show, die, move, explode,
change color, or do something else, then
BroadcastMessage
is your friend.
With
BroadcastMessage
, you simply send a message (invoke) a function
on the components of a single GameObject (as with
SendMessage
), but
BroadcastMessage
will proceed to cascade that invocation downward to all child
GameObjects automatically in the scene hierarchy (see Figure
3-7
).
This function accepts two arguments: