Graphics Reference
In-Depth Information
2. GameObject referencing using SendMessage.
SendMessage is a great way to send a message to a gameObject and call a func-
tion in one of its attached scripts or components when we do not need any kind of
return result. For example,
SomeGameObject.SendMessage("DoSomething");
SendMessage may also take several parameters, such as setting whether or not the
engine should throw an error when there is no receiver, that is, no function in any
script attached to the gameObject with a name matching the one in the SendMessage
call. (SendMessageOptions). You can also pass one parameter into the chosen func-
tion just as if you were passing it via a regular function call such as
SomeGameObject.SendMessage("AddScore",2);
SomeGameObject.SendMessage("AddScore",
SendMessageOptions.RequireReceiver);
SomeGameObject.SendMessage("AddScore",
SendMessageOptions.DontRequireReceiver);
3. Static variables.
The static variable type is useful in that it extends across the entire system; it will
be accessible in every other script. This is a particularly useful behavior for a game
control script, where several different scripts may want to communicate with it to
do things such as add to the player's score, lose a life, or perhaps change a level.
An example declaration of a static variable might be
private static GameController aController;
Although static variables extend across the entire program, you can have private
and public static variables. Things get a little tricky when you try to understand
the differences between public and private static types—I was glad to have friends
on Twitter that could explain it all to me, so let me pass on what I was told:
Public static
A public static variable exists everywhere in the system and may be accessed from
other classes and other types of script.
Imagine a situation where a player control script needs to tell the game con-
troller script whenever a player picks up a banana. We could deal with it like this:
1. In our gamecontroller.cs game controller script, we set up a public static:
public static GameController gateway;
2. When the game controller (gamecontroller.cs) runs its Start() function, it
stores a reference to itself in a public static variable like this:
gateway = this;
3. In any other class, we can now access the game controller by referring to its
type followed by that static variable (GameController.gateway) such as
GameController.gateway.GotBanana();
Search WWH ::




Custom Search