- Home /
Play a sound only once?
I have a script attached to an empty game object that waits until the player is at a distance of 10 from it, then plays a sound. The only problem is that when I get close to the game object the sound starts repeating and doesn't stop. How can I make it so the sound just plays once and never again? I've been looking around for solutions for hours now, and I've tried everything I can think of, but nothing works right.
var player : GameObject;
var VoiceClip : AudioClip;
function Start() {
player = GameObject.Find("lindamayfield");
}
function Update(){
//If the player is close then play the sound
if(Vector3.Distance(transform.position, player.transform.position) < 10)
{
audio.clip = VoiceClip;
audio.Play();
}
}
Answer by Comaleaf · May 01, 2012 at 08:39 PM
You could use a Collider to on trigger when the player enters the collider (using `OnCollisionEnter`).
Alternatively you could keep track of whether the sound has already been triggered like so:
var player : GameObject;
var VoiceClip : AudioClip;
var hasPlayed = false;
function Start() {
player = GameObject.Find("lindamayfield");
}
function Update(){
//If the player is close then play the sound
if(Vector3.Distance(transform.position, player.transform.position) < 10)
{
if (hasPlayed == false)
{
hasPlayed = true;
audio.clip = VoiceClip;
audio.Play();
}
}
else
{
hasPlayed = false;
}
}
(This assumes you'd want the sound to be able to play again when the player leaves the area, otherwise just remove the bottom hasPlayed = false;
)
Thank you! This works perfectly! I spent hours trying to figure this out and all I had to do was just add a few simple commands. Thanks again.
Answer by LukaKotar · May 01, 2012 at 09:25 PM
var player : GameObject; var VoiceClip : AudioClip;
function Start() { player = GameObject.Find("lindamayfield");
}
function Update(){
//If the player is close then play the sound
if(Vector3.Distance(transform.position, player.transform.position) < 10)
{
audio.PlayOneShot(VoiceClip);
}
}
PlayOneShot
does not make an AudioSource
only play once. What it does do is play a particular clip on an audio source without you having to set that clip to be the AudioSource
's clip.
If you call PlayOneShot
multiple times, it will play multiple times.
Your answer
![](https://koobas.hobune.stream/wayback/20220613070955im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Audio mixed, blending on distance ? 1 Answer
FMOD Distance Parameter: At 0 distance the sound is very quiet when it's supposed to be full volume? 0 Answers
Sound volume doesn't change no matter what distance? 0 Answers
3D Sound Max Distance Not Working. 0 Answers
Need help making an audio trigger. 2 Answers