Game Development Reference
In-Depth Information
Step 19: Open the HallwayDoorsTriggerScript.
Step 20: Add a variable to store the object that emits the sound and a line
to play it. Note that there are two lines in italics here:
var door : GameObject;
var doorOpenSound : GameObject;
function OnTriggerEnter (other:Collider){
iTween.RotateTo(door, Vector3(0,-120,0), 5.0);
doorOpenSound.audio.Play();
}
Why?
The public variable declaration allows us to define (for each trigger
down the road) the actual object that the sound belongs to (and it
can be a different sound for each door). The last line of code there says,
“go find the doorOpenSound, find the audio attached to it, and
play it.”
Step 21: Save and return to Unity. Fix any syntax errors that pop up in
the console. Populate the door variable for the script by dragging the
door that is to open from the Hierarchy view to the variable entry in the
Inspector.
Step 22: Test. Make any adjustments to the Audio Source component
that you feel is needed to make the sound softer/louder, and so on.
Cleaning Up with Destroy and Booleans
So the sound now runs as the door opens. The only problem here is that the
trigger is still sitting there. Now, if part of the game included shutting the door
as well, this could be good as the trigger could check the state of the door
and close it if it were open when we passed through it again. However, in this
case, there is little need for this trigger since the door doesn't do anything
else after this. With just a little bit of extra code we can get rid of elements
(GameObjects and or components) that we simply won't have need of later in
the game. This keeps the game snappy because Unity has less to keep track of,
and importantly makes sure that these triggers aren't used later.
But, sometimes we might not want to destroy a trigger. Perhaps there are
times when the trigger is meant to play a thump or something every time
the player walks up to it (for instance a locked door). It would do no good to
destroy the trigger after our first approach. So in our script we'll build in a
switch that allows us to tell the script on a case by case basis if it's to destroy
the trigger or not.
Booleans are either true or false; think of them as a switch. They can keep track
of whether a state of being is true or false. Once this state is remembered or
available, scripts can check with it to see if they should execute a particular
task based upon the Boolean state.
 
Search WWH ::




Custom Search