Play audio clip on camera from another gameobject

Hi, I have two Audio Sources on my camera. One is playing music, and the other one is playing a sound when I click on the surface. I have a script on my terrain object which is checking if I click on the terrain, and if I do it’s supposed to play the little “ding” sound. I’ve positioned the sound on the camera to hear it good, and now I wonder how I can assign that clip to be activated by another gameobject, my terrain. I though I would just have to drag the audio clip to a variable and play by using audio.PlayOneShot(sound1);, although this didn’t work, because it seems like I can’t drag an Audio source from one gameobject to another. It’s important to hear the sound good, so that’s why it has to be 2 sources on the camera.

Can you please tell me what I should do to play ONE audio source on my camera from a script on my terrain?


You could have two ways of doing it.

First you can have a second audio source on your camera. IF you have only one audio source, it should be for the music, if you swap the audio clip, you lose the music.

So you have a second one on your camera but bam, if you use GetComponent you are not sure which it will return.

So to fix this you could have an empty game object (name it ClickOnCam for ex) attached to the camera with the Audiosource. Then your script goes as:

AudioSource audioSource;
public AudioClip clickClip;
void Start(){
   audioSource = Camera.main.transform.Find("ClickOnCam").GetComponent<AudioSource>();
   audioSource.clip = clickClip;
void Update(){

the other way is to use

AudioSource.PlayClipAtPoint(clickClip, Camera.main.transform.position);

this will create a new Audio source object that will get destroyed automatically once the clip is done.

You can resolve this easily, in import settings of your audio file, just uncheck “3d sound” and add the audiosource to your terrain.

But, to play another Audiosource in Camera…

AudioSource[] allAudios = Camera.main.gameObject.GetComponents<AudioSource>();

allAudios is a array with all audiosources in the camera, so if it doeen’t play the right one, just change the index in array… allAudios[0], allAudios[1], allAudios[2] etc…