Game Development Reference
In-Depth Information
Component interactions
We've seen the anatomy of a
GameObject
as a collection of components and nothing
more. This raises logistical issues about how components should interact and
communicate with each other. Each component is effectively implemented as a
self-contained script file, separate from any other component, yet a component must
often interact with others. Specifically, you'll often need to access variables and call
functions on other components on the same
GameObject
, and you might even need
to do this on every frame. This section explores such intercomponent communication.
One way to call functions on other components is to use
SendMessage
and
BroadcastMessage
, as shown in
Chapter 1
,
Unity C# Refresher
. These functions are
type agnostic. Specifically, they're functions we might call anywhere in the script
to invoke methods by names on
all
other components attached to the same object,
regardless of their type. These functions don't care about the component type at all.
This makes both
SendMessage
and
BroadcastMessage
convenient to use. However,
the problem with them is twofold. First, they're an all or nothing affair; we might call
a function by name on all components or on none at all. We can't pick and choose
which component the message is dispatched to, because it's always dispatched
to them all. Second, both methods (
SendMessage
and
BroadcastMessage
) rely
internally on reflection, which can cause performance issues when used often,
such as by calling these functions in
Update
events or, even worse, in
OnGUI
events.
For these reasons, seek to use alternative methods wherever practically possible.
Let's consider these in the following sections.
GetComponent
If you need direct access to a specific and single component on an object and you
know its data type, try using
GetComponent
as shown in the following code sample
3-1. This function gives you access to the first component of a matching type attached
to a
GameObject
. Once you get a reference to it, you can access the component like
any regular object, setting and getting its public variables and invoking its methods:
01 using UnityEngine;
02 using System.Collections;
03 //-----------------------------------------------------
04 public class MyCustomComponent : MonoBehaviour
05 {
06 //Reference to transform of object
07 private Transform ThisTransform = null;
08 //-----------------------------------------------------
09 // Use this for initialization
10 void Start ()