- Home /
How do you prevent audio from being played multiple times when using raycast? (JS)
Hello Everyone,
I'm currently trying to prevent my audio from playing multiple times whenever the player interacts with one of the my gameobject's, however I'm having difficulties on doing so.
I'm using a raycast system that whenever the player presses the "E" or "left mouse", this allows him to interact with several objects in my scene. In particular interacting with one of a wardrobe door will cause it to open. Interacting with it once again will cause it to close instead, and vice versa... Therefore as you can see from the code below, I created some booleans to allow the door to open and close, but also added the yield WaitForSeconds (transform.parent.animation.clip.length);
to prevent the player from interrupting their animations.
This code is indeed working perfectly however I'm having some trouble to prevent the audio from being played multiple times whenever the player repeatedly presses the usage key. I did look into audio.length, however such attempts were unsuccessful. Therefore I'm asking if anyone knows any other methods where i can achieve this or perhaps I should retry the audio.length command?
Thank you!
#pragma strict
private var cupisOpen : boolean = false;
var WarAOpen : boolean = false;
var WarBOpen : boolean = false;
var CupOpenSound : AudioClip;
var CupCloseSound : AudioClip;
function WarOpen1 () {
if (!WarAOpen){
transform.parent.animation.Play("War1Open");
audio.PlayOneShot(CupOpenSound);
yield WaitForSeconds (transform.parent.animation.clip.length);
WarAOpen = true;
}else{
transform.parent.animation.Play("War1Close");
audio.PlayOneShot(CupCloseSound);
yield WaitForSeconds (transform.parent.animation.clip.length);
WarAOpen = false;
}
}
function WarOpen2 () {
if (!WarBOpen){
transform.parent.animation.Play("War2Open");
audio.PlayOneShot(CupOpenSound);
yield WaitForSeconds (transform.parent.animation.clip.length);
WarBOpen = true;
}else{
transform.parent.animation.Play("War2Close");
audio.PlayOneShot(CupCloseSound);
yield WaitForSeconds (transform.parent.animation.clip.length);
WarBOpen = false;
}
}
Answer by llSalvationll · May 06, 2013 at 11:24 PM
Use the isPlaying function of the animation. Given what you've got, try something like this if(!transform.parent.animation.isPlaying("War1Open") && !transform.parent.animation.isPlaying("War1Close")) { // play your sound } http://docs.unity3d.com/Documentation/ScriptReference/Animation.IsPlaying.html
Thanks for the replay, however I'm receiving the following error: It is not possible to invoke a type expression of type boolean.
Your answer
Follow this Question
Related Questions
How to play several audio cllips one after another. 3 Answers
i have a error that can not play a disabled audio source 1 Answer
Audio script doesn't work 0 Answers
Audio after Audio Loop 1 Answer
Play back multi channel audio 0 Answers