- Home /
Making a sound play only once with a Boolean variable in javascript
I'm very new to coding, and I'm having problems setting my code to play only on the first collision with the box collider.
Here's the code so far.
var Sound : AudioClip;
audio.loop = false;
function OnTriggerEnter(){ audio.PlayOneShot(Sound); }
I've been told to set the variable as a boolean that sets it to play only on the initial collision, but all the help that's available online is concerning things logging in, rather than this.
Any help would be wholeyl appreciated, thanks very much
Answer by Piflik · May 13, 2012 at 02:28 PM
As being said, add a boolean to test against.
private var hasPlayed : boolean = false;
function OnTriggerEnter() {
if(!hasPlayed) {
audio.PlayOneShot(Sound);
hasPlayed = true;
}
}
Hey Piflik,
That works perfectly, thanks very much. I'm learning more and more about this as this project goes on. Thanks
Your answer
Follow this Question
Related Questions
AUDIO ISSUES - PlayOneShot... is cutting short... I think? 2 Answers
Alternate between two Audio clips on collision 3 Answers
Wait until audio is finished before set active is false 2 Answers
Need help making an audio trigger. 2 Answers
Get an object to play a sound if player rolls over a trigger. 2 Answers