- Home /
Play audio only once in trigger collision entry?
I've been scouring the forums for an answer, but just can't figure it out. I'm a novice w/ javascript in Unity, and feel like it is a VERY easy answer! I have a box collider that triggers the "narration sound game object" and makes the "journal game object" disappear. At the end of the narration, it makes another trigger appear (exitDoor gameobject), that allows the player to leave the room.
Everything works great with the audio, the journal object, and the exit door trigger, but the problem arises when I enter the trigger, it starts the 30-second narration, and while I'm walking around the space, if I re-enter the trigger (which happens all the time), it starts the audio over again! I only want the audio to play once. I've pasted my script below.
Many thanks everyone!
var narrationSound : GameObject;
var destroyWhenFinished : boolean;
var exitDoor : GameObject;
var journal : GameObject;
function Start (){
exitDoor.SetActive (false);
}
function OnTriggerEnter (other:Collider){
journal.SetActive (false);
narrationSound.audio.Play();
yield WaitForSeconds (narrationSound.audio.clip.length);
exitDoor.SetActive (true);
if (destroyWhenFinished){
Destroy (narrationSound);
Destroy (gameObject);
}
}
Answer by Aerozo · Jun 14, 2014 at 03:11 PM
Easy indeed.
First, add a boolean at the top
var narrationSoundPlayed : boolean;
Then right at the beginning of your OnTriggerEnter() function, add these two lines:
if(narrationSoundPlayed) return;
narrationSoundPlayed = true;
Should be fairly self-explanatory but drop a comment if you'd like me to explain it.
YOU ROC$$anonymous$$, Aerozo! $$anonymous$$any many thanks on this quick answer - it works perfectly! I owe you one!
Your answer
Follow this Question
Related Questions
OnTriggerEnter() not recognizing collider 1 Answer
Detect if out of trigger 2 Answers
one shot Sound on collision. Unity 4.0 problem. 2 Answers
Action activates trigger. 1 Answer
Adding Sound To Collectable Object 1 Answer