Make sound follow camera on trigger?

I have a trigger set up and I want it to play music when I step on it, it works. But when I move away the music stays in the same place. Is there anything I can add to this script to make it follow the camera?

private var soundPlayed : boolean = false;
var Laugh : AudioClip; 
var volume: float = 10.45;
var LightOff : AudioClip; 
var ObjToDestroy : Light;
var ObjToDestroy2 : Light;
var ObjToDestroy3 : Light;
var ObjToDestroy4 : Light;
var ObjToDestroy5 : Light;
var ObjToDestroy6 : Light;
var ObjToDestroy7 : GameObject;
var Music : AudioClip;

function OnTriggerEnter(col : Collider){ //Play Sound if player enters trigger
  if (!soundPlayed && Laugh) { // but only if it has not played before
    AudioSource.PlayClipAtPoint(Laugh, transform.position, 10.4);
    soundPlayed = true; // sound will not play anymore
    audio.PlayOneShot(LightOff); 
   Destroy (ObjToDestroy);
   Destroy (ObjToDestroy2);
   Destroy (ObjToDestroy3);
   Destroy (ObjToDestroy4);
   Destroy (ObjToDestroy5);
   Destroy (ObjToDestroy6);
   Destroy (ObjToDestroy7);
   AudioSource.PlayClipAtPoint(Music, Camera.main.transform.position);
   }
   }

I've not used Unity audio yet, but looking at the help I imagine your AudioSource that should follow the camera should be attached to the same game object as your camera, and you should use Play() instead of PlayClipAtPoint().

Hello Joorst, Can you help me with the line of code because i changed to persistentdataPath but still the screenshot is not showing when i m running on the standalone application.

1 Answer

1

PlayClipAtPoint plays the sound at the defined position - but if you move the sounds remain there. You should add an AudioSource to the player, and play the sound using Play():

...
    Destroy (ObjToDestroy6);
    Destroy (ObjToDestroy7);

    if (col.audio){ // if the player has an AudioSource...
       col.audio.clip = Music; // set its clip to Music...
       col.audio.Play(); // and play it
    }
  }
}

Or maybe make it a 2D sound.