How to disable a game component (audio)
Hi guys i am creating a quizz game for android . Every time you click on a good answer there is a sound . I want to make a option scene where you can disable the sound. I want to know how i do this using script, for example when i press a button the game component with the sound is disable
Answer by Statement · Mar 08, 2016 at 09:30 PM
Note that you can also just simply call AudioSource.mute through the button:
If you just want to toggle mute, make a small script that does exactly that:
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class AudioSourceMuteToggler : MonoBehaviour
{
public void ToggleMute()
{
var a = GetComponent<AudioSource>();
a.mute = !a.mute;
}
}
If you want explicit control over Play(), a simple skeleton class could be this:
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class MuteableAudio : MonoBehaviour
{
bool isMuted;
public void Mute()
{
isMuted = true;
GetComponent<AudioSource>().Stop();
}
public void Unmute()
{
isMuted = false;
}
public void Play()
{
if (!isMuted)
GetComponent<AudioSource>().Play();
}
}
Then you can call Mute, Unmute or Play on this script instead of AudioSource. If you want to control multiple audio sources with the same script, make the boolean static. If you want more fine grained control over audio groups, consider using AudioMixers with exposed parameters (SetFloat) for Attenuation/Volume.
You can also disable the AudioSource component instead of explicity controlling a boolean variable but that will give you warnings when you call Play, and I am not a big fan of warnings. It's up to your preference.
Your answer
Follow this Question
Related Questions
Quick Audio Question - Trying to add sound to gun 2 Answers
How do I access the instance of a script held by a GameObject? 2 Answers
Click on object shows menu, but also move it. 0 Answers
My Character randomly stops moving in game. 0 Answers
How do i make a game object grow by absorbing another game object ? 0 Answers