- Home /
 
Sound plays once close to an object
I've seen a lot of scripts that play a sound once you collide with an object, but I need one that makes a sound play once you come close to a specific object. I also need it to work on multiple objects throughout one level. Can someone help me with a script?
Answer by fafase · Apr 08, 2012 at 03:25 PM
You can compare the distance between the player and the object with distance() function and then when the guy gets in the range, play the sound.
 var other : Transform;
 var range:int;
 var sound:AudioClip;
 var played:boolean;
 var timing:int;
 var delay:int=10;
 
 function Start(){
 played=false;
 timing =Time.time;}
 
 function Update(){
 if (Vector3.Distance(other.position, transform.position)<range) {
       if(timing<Time.time){
            played = true;
            timing = Time.time + delay;}
   }
 if(played){
 AudioSource.PlayClipAtPoint(sound, transform.position);
 played=false;
 }
 
              Thank You! This helps so much! Is this a way to make it so the sound dosen't loop?
I'm having trouble implmenting the audio.loop = false into the script. After messing with errors for 10 $$anonymous$$utes I was led to if(played){ audio.loop = false; at the end of the script, but that still continued to loop the sound. I would I implement if(played) : audio.loop = false into the scipt?
No the pb comes frm the fact that played gets back to true right on. $$anonymous$$y mistake. I updated with a ti$$anonymous$$g. Now the sound will happen every 10 sec.
This script is AWESO$$anonymous$$$$anonymous$$..Is it posible to add if you spot or look at enemy then it plays the sound.I was trying to set it,I have even checked tutorials but I can't get it right.I must be doing something wrong.If you find the way to set it,could you please post a complete script-it would mean a lot to me.-thanks (sorry for my bad English)
Your answer