- Home /
No overlapping sounds
Hey guys,
quick question (I hope). How do I stop audio clips from overlapping? I'm creating a Pacman game, and when Pacman eats a candy, I want a sound to play. However, if an eating sound is still playing, I dont want the new sound to start. Only if one eating sounds is completed, and Pacman eats another candy, I want the clip to play again. Partial piece of my code for this:
public AudioClip candy;
void OnTriggerEnter(Collider other)
{
if (!pause)
{
if (other.gameObject.tag == "PickUp")
{
other.gameObject.SetActive(false);
if (!audio.isPlaying)
AudioSource.PlayClipAtPoint(candy, transform.position);
count = count + 1;
score = score + 10;
//scoreText.text = "Score: " + score;
if (count >= totalPickupCount)
{
if (!fail)
{
timeScore = Mathf.FloorToInt(10 * startTimer);
liveScore = Lives.lives * 100;
}
storeEndScore();
storeEndTimeScore();
storeEndLiveScore();
Application.LoadLevel("Score"); //Game is klaar - ga naar Score Scherm
}
}
}
As you can see, i treid using audio.isplaying. However this has no effect. Any other ideas/options?
Hi, please check your code once more. Like adding curly brackets around: AudioSource.PlayClipAtPoint(candy, transform.position); count = count + 1; score = score + 10;
Is not needed, since count = count + 1 shouldnt be in the if statement :)
audio, and AudioSource.PlayClipAtPoint I believe don't use the same AudioSource, and I think isPlaying is a flag for if you have it paused anyway.. But if you use your own AudioSource ins$$anonymous$$d, you can check what's playing by checking it's output data and see if it's playing anything. Here is a function that does it.
bool isPlaying(AudioSource p) {
float[] samples = new float[1024];
audio.GetOutputData(samples, 0);
for(int l = 0; l < 1024; l ++) {
if (samples[l] != 0) return true;
}
return false;
}
Alternatively you could also set a flag to say if your playing audio, to unset the flag check the length of the audio, and with a timer unset after that length.
I think $$anonymous$$pjComp is on the right track here. The :
if (!audio.isPlaying) {
Will only check if the Audio Source that is on the same object that the script is on is Playing. If you want to check for a playing audio source on another object you need to reference that object like :
if (!$$anonymous$$y_Other_GameObject.audio.isPlaying) {
I can't comment on the play clip at point, never used it sorry.
$$anonymous$$rSoad you a right here, the docs for isPlaying I would say is wrong though. >> AudioSource.isPlaying will return false when AudioSource.Pause() is called.. isPlaying does indeed return false when audio has stopped playing too, not just when pause is called. So my isPlaying function is not needed. Just using an AudioSource ins$$anonymous$$d of PlayClipAtPoint does the trick.