Button that toggles On/Off Sound/Audio

i searched for related topics for my problem, they seems useful but i cant implement in my project, i cant find the logic in their answers. so simple question. i have this button which is a “Speaker On” Icon. if i clicked this, the icon will change to Speaker Off and all the sound in my scenes will be turn off. btw, my background music is in my first scene(main scene) and it is attached to empty game object. here is the code i got so far.
public var SoundClip : AudioClip;
private var SoundSource : AudioSource;

function Awake()
{
DontDestroyOnLoad(gameObject);
SoundSource = gameObject.AddComponent(AudioSource);
SoundSource.loop = true;
SoundSource.volume = 0.8;
}
 
function Start()
{
SoundSource.clip = SoundClip;
SoundSource.Play();
}

can someone help me please? it would be very much appreciated.

1 Answer

1

You could use the OnMouseOver function and audio.PlayOneShot(audioName); and to stop all audio use audio.stop(); Here’s what I did make sure you have an audiosource on the object.

var clip1 : AudioClip;
var clickNum = 0;

if (clickNum == 0){
	renderer.material.color = Color.green;
	audio.Stop();
	}
function OnMouseOver () {
	if (Input.GetMouseButtonDown(0)){ //check if mouse button is pressed while on object
		clickNum += 1;
		if (clickNum == 2){
			clickNum = 0;
			}
		if (clickNum == 0){
			audio.Stop();
			renderer.material.color = Color.green;
			}
		if (clickNum == 1){
			audio.Stop();
			audio.PlayOneShot(clip1);
			renderer.material.color = Color.red;
			}
		}
	}