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();
}
}
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;
)
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);
}
}