- Home /
How do I mute one sound source using another?
I have a cube which emanates sound. I want to make it so that when my First-person camera controller passes through another cube, the sound of the first cube mutes.
The challenge I'm facing here is that I think I need to place a script on the second cube that points to and controls the mute controls on the first cube.
This seems pretty basic, but I don't know the way forward. I've tried using the Accessing Other Game Objects tutorial and was able to locate the first cube from the second using a tag. However, I'm not entirely sure where to go from here or whether that was even the right approach to begin with.
Any help would be appreciated! For what it's worth, I'm using C Sharp but am open to using either JS or CS for this.
thanks
-g
I think you are on the right track. If it is just two objects you want to communicate with each other, I would simply create a public void $$anonymous$$uteSound()
or similar on one, and have the other call it as needed.
For this approach, I would avoid using tags, ins$$anonymous$$d have a public YourScriptName otherCube
variable in the caller cube, and set it via the inspector, so you would be able to simply do otherCube.$$anonymous$$uteSound()
But, all this is a little too rigid, if you want to have more objects. In this case, I would use events. If you are new to this, and don't want to spend too much time on learning it, you may want to start with Send$$anonymous$$essage
and only later try your luck with events.
CubeA = cube with sound CubeB = cube muting CubeA sound
Add collider on cubeB and set it to isTrigger. Put a script on it like so:
public AudioSource cubeASound;
private void OnTriggerEnter(...){
cubeASSound.mute = true;
}
You need a ridgidbody to be able to catch triggers. So put a rigidbody on CubeB or on the object passing through CubeB.
This worked like a charm, thanks! Creating the object cubeASound was the missing step for me.
Answer by Tomer-Barkan · Nov 07, 2013 at 04:21 PM
Put a script on your character that keeps a reference to the current playing source. When colliding with the new source, stop the old one, start the new one, and keep a reference to the new one instead.
private AudioSource currentlyPlaying = null;
void OnTriggerEnter(Collider other) {
AudioSource newSource = other.GetComponent<AudioSource>();
// if collided with an object that has audio source
if (newSource != null) {
// disable previous source if exists
if (currentlyPlaying != null) {
currentlyPlaying.Stop();
}
// activate new source and keep reference
currentlyPlaying = newSource;
currentlyPlaying.Play();
}
}
This is really helpful, thanks everyone! I'll let you know how it goes. -g
Your answer
![](https://koobas.hobune.stream/wayback/20220613121412im_/https://answers.unity.com/themes/thub/images/avi.jpg)