- Home /
Checking if audio PlayClipatPoint already playing?
Is there a way to check if an audio using PlayClipatPoint is already playing and if not play that clip?
Answer by aldonaletto · Sep 09, 2013 at 04:41 AM
Unfortunately, PlayClipAtPoint doesn't return a reference to the temporary AudioSource it creates, thus we can't check whether it's playing. A simple (although ugly) solution is to GameObject.Find an object called "One shot audio" (that's the name PlayClipAtPoint gives to the temporary game object it creates) - if not found, the clip has finished:
if (!GameObject.Find("One shot audio")){ // if no temporary audio source...
AudioSource.PlayClipAtPoint(....); // play the sound
}
Besides being inelegant, the sound won't be played if there are other temporary AudioSources alive.
If you want to play the sound continuously, a better solution is to repeat the sound at the suitable rate:
var sound: AudioClip;
private var tSoundEnd: float;
function Update(){
if (Time.time > tSoundEnd){ // if previous clip has finished playing...
AudioSource.PlayClipAtPoint(sound, ...); // play a new one...
tSoundEnd = Time.time + sound.length; // and calculate time for next
}
}
Finally, you could create your own PlayClipAtPoint function: it could return a reference to the game object created, and when it became null you would know that the clip wasn't playing anymore:
public var sound: AudioClip;
private var curTempAudio: GameObject;
function PlayClipAt(clip: AudioClip, pos: Vector3): GameObject; {
var tempGO = GameObject("TempAudio"); // create the temp object
tempGO.transform.position = pos; // set its position
tempGO.AddComponent(AudioSource); // add an audio source
tempGO.audio.clip = clip; // define the clip
tempGO.audio.Play(); // start the sound
Destroy(tempGO, clip.length); // destroy object after clip duration
return tempGO; // return reference to the temporary GameObject
}
function Update(){
if (!curTempAudio) curTempAudio = PlayClipAtPoint(sound, transform.position);
}
Thanks aldonaletto! Funny I already use this awesome technique in another script and forgot.
I should probably also point out that I have a huge swarm of enemies that surround main character and each had a script to play a sound. I ran into serious issues when all 30 starting playing their same sound. So now I'm trying to find a way that if one of the enemies plays the sound the others don't.
I think I can get this to work.
Your answer
Follow this Question
Related Questions
AudioSource.PlayClipAtPoint 1 Answer
Audio Clip Getting Cut Short 1 Answer
A better script for a machine gun? 1 Answer
Why won't 3d sounds play anywhere near 100% volume? 1 Answer
Making AudioSource follow camera? 1 Answer