Game Development Reference
In-Depth Information
Step 2: Create two empty GameObjects (GameObject>Create Empty).
Name one Sound-Footsteps and the other Sound-Gunshot.
Step 3: Make both of these children of FPC_AegisChung (go ahead and
continue through the breaking prefab warning).
Step 4: For each, add an Audio Source component (Component>Audio>
Audio Source).
Step 5: Define the sound for each by dragging the desired sound from the
Project panel to the Audio Clip input field for the Audio Source component.
Step 6: For Sound-Footsteps, be sure to disable the Audio Source
component (the footsteps script simply turns it on when needed). Be sure
Play on Awake and Loop are both checked.
Step 7: Drag the SoundFootstepsControl script (that we wrote back in our
sound chapter and should currently be in the Project panel) onto Sound-
Footsteps (you'll be warned about breaking a prefab). The footsteps
should be done. Play to make sure and adjust the volume to taste.
Step 8: For Sound-Gunshot we're going to run things a bit differently. Leave
the Audio Source active, but turn off Play on Awake (also, leave Loop off ).
Step 9: Open AC_ToolFunctionalityScript and create two variables—
one for the GameObject that contains the audio (we'll call it
gunshotSoundSource) and one for the actual AudioClip (we'll call this
one gunshotSound). So at the top of the script add these two variables:
var gunshotSoundSource : GameObject;
var gunshotSound : AudioClip;
Why?
We'll be using the function PlayOneShot to trigger the sound (just looking
at many different ways to handle sound). PlayOneShot requires an object, its
audio component, and the specific audio clip to play. While we could declare
these variables within the body of the script, it can be easier to tell what's
going on in a script sometimes when the variables can be quickly read up top.
Step 10: Find the place where the player fires the gun in the script
( Figure 15.22 ). Add the following line:
gunshotSoundSource.audio.PlayOneShot(gunshotSound);
Why?
This line finds the object gunshotSoundSource, finds its audio
component, and plays the audio clip gunshotSound once.
Step 11: Save and return to Unity. Fix any syntax errors that the Console
complains about.
Step 12: Populate the two new variables. For gunshotSoundSource, drag
Sound-Gunshot from the Hierarchy to the Gunshot Sound Source input
field in the Inspector. For the Gunshot Sound input field, drag the file from
the Project panel (it's the easiest way to get the name right).
Search WWH ::




Custom Search