Game Development Reference
In-Depth Information
If you're thinking ahead to beginning with an empty game object, adding an Audio Source
component, then dragging the Fantasy Victory (free) audio clip into the Audio Clip property, you
would be right. Even better, Unity has a few handy shortcuts to save you those steps.
Drag and drop the Fantasy Victory (free) audio clip into the Hierarchy. Be sure to drop it between
game objects, not on a game object (that would appear highlighted). The Fantasy Victory (free) game
object will appear in the Hierarchy, with an Audio Source attached and the Fantasy Victory (free)
audio clip already assigned to the Audio Clip property.
Drag the clip again into the Scene view, and notice that a green circle with a + symbol appears as
you drag it over other game objects in the scene. If you drop the audio clip onto a game object,
Unity will create an Audio Source component and attach it to the game object automatically. Be
careful—if the game object already has an Audio Source with an assigned clip and you drop this one
onto it, the new audio clip will replace the previously assigned audio clip. Don't actually drop Fantasy
Victory (free) into the Scene view right now. If you already did, use the Remove Component option
to delete it so you have only the first one, made up of a Fantasy Victory (free) game object with only
Transform and Audio Source components.
Move this game object to a Transform position of (0, 11.5, 150), putting it centered at the top of the
final ramp. If you were to playtest now, the clip will play immediately since Play On Awake is checked
by default. Uncheck it in the Inspector. While still in the Inspector, select Add Component ➤
Physics ➤ Box Collider. Check IsTrigger, and change the values of Center to (0, 1, 0) and Size to (8, 2, 0.2).
You'll need a script to play the audio when the player comes into contact with this trigger collider, so
in the Inspector select Add Component ➤ New Script and name it VictoryMusic, then click Create
and Add. Recall that this method of creating a new script creates it in the Assets root folder. Keep
your project organized by moving it to the Assets ➤ Scripts folder, then open it in MonoDevelop. Edit
the code to the following:
#pragma strict
public var backgroundMusic : GameObject;
function OnTriggerEnter () {
backgroundMusic.GetComponent(BackgroundMusic).PlayVictoryMusic();
}
You've seen this kind of code before. It breaks down as follows:
(1) public var backgroundMusic : GameObject;
Declare a public reference variable backgroundMusic of type GameObject that
will be used to hold a reference to the Audio game object.
1.
(2) function OnTriggerEnter ()
When the player character enters the collider volume, OnTriggerEnter() is
called since the collider is set to IsTrigger.
2.
(3) backgroundMusic.GetComponent(BackgroundMusic).PlayVictoryMusic();
Search WWH ::




Custom Search