- Home /
Audio is repeating.
Hi!Can you please fix my code?My problem is when you click on text(with box collider) audio sonds,but if you click it 2x or more fast same audio sounds many times.I want to make,when you press one of the text(which plays audio)you can't press it again when it sounds or other audio.**
I need to make that when audio sounds,you can't turn on other audios until you 1st stops to sound.And if audio is pressed and you press it again,it stops.
#pragma strict
var isQuitButton = false;
var sound : AudioClip;
function OnMouseDown()
{
renderer.material.color = Color.red;
audio.PlayOneShot(sound);
waitForAudio(audio.clip.length);
}
function waitForAudio( time:float){
yield WaitForSeconds(time);
//change color back
renderer.material.color = Color.white;
}
If I understand your question correctly, you want to click the text and have audio play, and while the audio is playing, clicking the text will not play any more audio. You can do this by storing the last time the text was clicked up top. Then, when the text is clicked again, simply do:
if (Time.time > lastTimeClicked + audio.clip.length) { audio.PlayOneShot(sound); }
Answer by Priyanshu · Jan 05, 2015 at 03:44 PM
Just add a bool which turns true when 'yield WaitForSeconds(time)' finishes.
And call 'WaitForSeconds' and 'audio.PlayOneShot' when that bool is true.
Try this:
var soundPlaying = false;
function OnMouseDown()
{
if( !soundPlaying)
{
renderer.material.color = Color.red;
audio.PlayOneShot(sound);
waitForAudio(audio.clip.length);
soundPlaying = true;
}
}
function waitForAudio( time:float){
yield WaitForSeconds(time);
//change color back
renderer.material.color = Color.white;
soundPlaying = false;
}
Answer by StephanM · Jan 05, 2015 at 03:34 PM
Try checking to see if it's already playing before allowing another click
function OnMouseDown() { if(!audio.isPlaying) { renderer.material.color = Color.red; audio.PlayOneShot(sound); waitForAudio(audio.clip.length); } }
Answer by adelphiaUK · Jan 05, 2015 at 03:51 PM
Different people have different approaches. First question is, do you have multiple or a single sound attached to the game object?
If you have a single audio source then I would use audio.Play() and make sure looping is disabled on the actual source.
function OnMouseDown() {
if(!audio.isPlaying) {
renderer.material.color = Color.red;
audio.Play();
waitForAudio(audio.clip.length);
} else {
waitForAudio(0.5); // ensure audio has completed
}
}
function waitForAudio(duration : float) {
if(audio.isPlaying) {
yield WaitForSeconds(duration);
}
renderer.material.color = Color.white;
}