Game Development Reference
In-Depth Information
40 //Get PlayerController object and update cash
41 PlayerController PC = Other.gameObject.GetComponent<PlayerController>();
42
43 //If there is a PC attached to colliding object, then update cash
44 if(PC) PC.Cash += CashAmount;
45 }
46 //--------------------------------------------------------------
47 }
Note
More information on Unity trigger events can be found at
http://docs.unity3d.com/
Lines 16-25.
The
Start
event demonstrates an important and useful function
in Unity, namely
GameObject.FindGameObjectWithTag
. Using this function, the
purpose of
Start
is to
search
through all game objects
in the scene
, finding an
object with a
tag
of “
sounds
”, and then to retrieve a reference to its
AudioSource
component, if it has one. This component will be used to play back any sounds
associated with this power-up when it's collected. The success of this function
depends on there actually being an object in the scene that has a tag of
“
sounds
” and an
AudioSource
component. Thus, if there isn't such an object,
be sure to add one. Thankfully, however, this power-up has been coded so
that if no such object is present, the power-up will simply not play a sound on
collection, as opposed to throwing an error or exception.
Note
I recommend taking a look at the
FindGameObjectWithTag
function on the Unity online
documentation. It can be really useful for retrieving references to objects at runtime by object
Lines 29-32.
The
OnTriggerEnter
function is inherited from
Component
, and is
executed automatically by Unity as an event, whenever a collision is detected
with the trigger. Here is where we should code a response to collision events.
The function argument
Other
is a reference to the object that is colliding with us,
and it's an important parameter for validating a collision. The power-ups for this
game should be collected by the Player only, and
not
by wandering Enemies.
But since both the Player and the Enemies will have colliders, both of them will
be able to collide with, and possibly collect, the power-up—unless we validate
the
Other
object! This validation occurs in line 32, where we check to see if the
colliding object is marked with the
"player"
tag. If it's not, then the event is
ignored. Consequently, for the collision functionality to work here, the
Player
object must be marked with the tag
"player"
.