- Home /
The question is answered, right answer was accepted
how can i mute all audio sources in the scene?
I already have a script attached to all the components that has an audio source, like the background music, the player's sounds and the enemy, who is a prefab. all sounds get mute when i press M, except for the enemy's sounds (hurt and death sounds). that's my script (c#):
using UnityEngine; using System.Collections;
public class Audio : MonoBehaviour {
AudioSource audio;
void Start() {
audio = GetComponent<AudioSource>();
}
void Update() {
if (Input.GetKeyDown(KeyCode.M))
if (audio.mute)
audio.mute = false;
else
audio.mute = true;
}
}
how can i mute the enemy sounds as well?
Answer by sleepandpancakes · Apr 04, 2017 at 05:05 AM
Why not just mute the audio listener? That way all sounds are muted at once.
public void ToggleSound()
{
toggle = !toggle;
if (toggle)
AudioListener.volume = 1f;
else
AudioListener.volume = 0f;
}
Answer by Hellium · Apr 03, 2017 at 04:47 PM
I would use one "Mute manager" instead of multiple attached to each objects.
FindObjectsOfType
is not resources efficient, and maybe, you can "cache it" instead of retrieving them each time. It depends on your project.
public class MuteManager : MonoBehaviour {
private bool muted ;
void Update()
{
if (Input.GetKeyDown(KeyCode.M))
ToggleAudio();
}
public void DisableAudio()
{
SetAudioMute( false ) ;
}
public void EnableAudio()
{
SetAudioMute( true ) ;
}
public void ToggleAudio()
{
if( muted )
DisableAudio();
else
EnableAudio();
}
private void SetAudioMute( bool mute )
{
AudioSource[] sources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
for( int index = 0 ; index < sources.Length ; ++index )
{
sources[index].mute = mute ;
}
muted = mute ;
}
}
the script is not working, the following error keeps appearing: Assets/$$anonymous$$ute$$anonymous$$anager.cs(37,12): error CS1061: Type UnityEngine.AudioSource[]' does not contain a definition for
mute' and no extension method mute' of type
UnityEngine.AudioSource[]' could be found. Are you missing an assembly reference?
He made a typo, try replacing line 34 with
sources[index].mute = mute ;
I fixed it and the error was gone, but it only mute the background music, what should i do?