- Home /
I want to make my audio play only once
I have a fence in my game and if my player collides with the fence, the audio of opening fence will be called. After that if my player collides with my fence, the audio will be played again. I don't want to make my audio play more than once. By the way my program is this.

Is there a way to know if the fence is open and constrain the audio.Play() to only a one shot if the fence isn't open? Does the fence have scripts attached to it?
Answer by TheCatProblem · Aug 27, 2014 at 03:11 PM
One way to accomplish this would be to simply have a boolean variable that gets checked before playing the sound and set when the sound plays. Something like this:
bool soundHasPlayed = false;
function OnCollisionEnter(){
if (!soundHasPlayed){
audio.Play();
soundHasPlayed = true;
}
}
where should I put the (bool soundHasPlayed = false;) bit? sorry, I am a beginner of unity
The declaration of soundHasPlayed would go inside your script class but outside of any functions (this makes it a member variable of your script class, which allows any function within your script - e.g., OnCollisionEnter - to access it).
You might find this tutorial video helpful. (In the script example below the video, the variable myInt is a member variable.)
How ever it says it needs a semicolon at the end when it is already there
What code gives you the semicolon warning/error? One point is that the code I've written is in C#; if you're using Unity's version of JavaScript the declaration would be var soundHasPlayed : bool = false; ins$$anonymous$$d.
Answer by Nick4 · Aug 27, 2014 at 03:09 PM
You mean OnCollisionEnter gets called twice? If that's the case, I'm not sure what it is but here's a work-around :
// If audio isn't already playing, play it.
if(!audio.isPlaying)
{
audio.Play();
}
Your answer