Unity 5 Sound repeating when detected by raycast JavaScript
Hello, I have a problem where if a person detects me by raycast he is supposed to stop speaking and then say to go away. Although it is on function update so the raycast detects it 100's of times and plays the sound over and over again. Is there any fix to this WITH raycasting?
(PLAYING THE SOUND)
var speech : AudioClip[];
var inside : boolean = false;
function Update()
{
if (Input.GetKeyDown("e"))
{
GetComponent.().PlayOneShot(speech[0]);
}
if(RaycastingDetection.audioz == true)
{
//GetComponent.().Stop();
GetComponent.().PlayOneShot(speech[1]);
(THE RAYCAST)
static var audioz : boolean = false;
var fwd1 : boolean = false;
function Start()
{
var audio: AudioSource = GetComponent.();
}
function Update()
{
var fwd: Vector3 = transform.TransformDirection(Vector3.forward);
if(Physics.Raycast(transform.position, fwd, 10))
audioz = true;
print ("Raycast Working");
}
Answer by TheyLeftMe4Dead · Jan 16, 2017 at 04:08 AM
I'm a bit confused with your format but think I can help. (Usually you would make separate functions for Update to call for readability.) The main issue I see is that you are checking if "RaycastingDetection.audioz == true" in the update function. If a person's ray is detecting you it will return true. Therefore if you keep standing in front of them, RaycastingDetection.audioz will stay true.
Because RaycastingDetection.audioz will stay true, and the Update function checks if it is true every frame, the audio will play continuously.
To fix this, I would recommend that you create a separate function called WaitForAudio(). You would call this after the person's audio "Go Away" starts to run. I would see it like this:
function WaitForAudio() {
GoAwayPlaying = true;
Yield WaitForSeconds(GoAway.length);
GoAwayPlaying = false;
}
Then, change your if statment like this:
If (RaycastingDetection.audioz == true && GoAwayPlaying = false) Play Audio; WaitForAudio();
Answer by Eimantas1 · Jan 17, 2017 at 11:26 AM
Thanks for the answer, this has been asked a while ago so I already found out a solution. My solution is to check if the audio source is playing by using "!" and if it is not then it plays a one shot sound. But thanks for the answer.