Game Development Reference
In-Depth Information
Messaging
Communication is a key factor in any game. A lot of times, we just use colliders or phys-
ics to notify two components that there is something to be aware of. This is a very basic
form of communication. Other times, we use referencing or (in the case of Unity) trawl
through the project's hierarchy to find another game object to communicate with or notify.
Unity has its own messaging-type functions, such as
SendMessage
and
Broad-
castMessage
. Both functions actually implement event-style code (as in the preceding
case) without actually declaring events, but they are
very
slow and shouldn't be used ex-
tensively.
The
SendMessage
function will call a named method on a game object (any method
with the same name) with a
single
optional parameter as follows:
void OnCollisionEnter(Collision col)
{
col.gameObject.SendMessage("IHitYou");
}
So, it will call the
IHitYou
method on whatever you will collide with. By default, this
will not cause an error to be raised if whatever you collide with does not have the
IHitYou
method. However, if you wish, you can change this by adding
SendMes-
sageOptions
when you call
SendMessage
, as follows:
void OnCollisionEnter(Collision col)
{
col.gameObject.SendMessage("IHitYou",
SendMessageOptions.RequireReceiver);
}
If you want to send a value (there can only be one) with the call, just add it after the meth-
od name and before
SendMessageOptions
(if set).
The
BroadcastMessage
method works in a similar way but will attempt to run your
selected method on the selected
gameObject
and
all
its children as follows:
void OnCollisionEnter(Collision col)
{