Game Development Reference
In-Depth Information
Note
More information on Unity colliders can be found at
Handling Collision Events: Getting Started
By using the Collider component of an object as a trigger volume, Unity can send all components on
an object an event call for each and every unique collision, allowing us to code custom responses
to the events when they happen. For Player collisions with the Cash Power-Up, we'll want to do the
following: first,
increase the amount of cash collected
in total for the Player; second,
play a collection
sound
; and third,
remove the power-up from the scene
so the Player cannot collect it more than
once. To handle this behavior, we'll code a new class that I'll call
Powerup_Dollar
. To implement this,
then, create a C# script file in the project named
Powerup_Dollar.cs
. Be sure to add this script as a
component of the Cash Power-Up in the scene. A good start for this class might look like Listing 4-11.
Listing 4-11. Powerup_Dollar.cs: Starting the Cash Power-Up Class
01 //-------------------------------------------------------------
02 using UnityEngine;
03 using System.Collections;
04 //--------------------------------------------------------------
05 public class Powerup_Dollar : MonoBehaviour
06 {
07 //Amount of cash to give player
08 public float
CashAmount
= 100.0f;
09
10 //Audio Clip for this object
11 public AudioClip
Clip
= null;
12
13 //Audio Source for sound playback
14 private AudioSource
SFX
= null;
15 //--------------------------------------------------------------
16 }
Lines 07-14.
The Cash Power-Up declares three variables, of which one is
private.
CashAmount
is a float expressing how much cash should be awarded to
the player when the power-up is collected. This allows us to specify different
values for each power-up, if we need to. The
Clip
variable will specify which
audio file to play when the power-up is collected. In Chapter 2, audio assets
were imported into the project, and for this power-up I'll be using the audio
file
powerup_collect.wav
. This file is included in the topic companion files, but
you can use any audio file you want. Finally, the
SFX
variable refers to an
Audio
Source component
, the component to play the
Clip
audio file. This component
acts like a media player.