The question is answered, right answer was accepted
How do I disable audio with a button and turn it back on?
Hello everyone,
I want to create a button that turns on and off audio, and have the image change at the same time. I have this button but when I click it the audio turns off and then right back on. I want it so that when I click it, it turns off. Then, when I click it the second time, it turns back on. And then for the third time, it goes back off, and so on. How would I do this? This is my script so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DisableMusic : MonoBehaviour {
public GameObject gameAudio;
public Button button;
public Sprite Image1;
public Sprite AudioOff;
public bool Onoroffaudio;
public void AudioController()
{
if (Onoroffaudio == true) {
button.GetComponent<Image> ().sprite = AudioOff;
gameAudio.SetActive (false);
Onoroffaudio = false;
Debug.Log ("Audio working");
}
if (Onoroffaudio == false) {
button.GetComponent<Image>().sprite = Image1;
gameAudio.SetActive (true);
Onoroffaudio = true;
}
}
}
Answer by upasnavig90 · Feb 13, 2018 at 05:57 AM
use toggle buttons and check:
if(toggle.isOn)
{
button.GetComponent().sprite = Image1;
m_MyAudioSource.Play();
}
else
{
button.GetComponent ().sprite = AudioOff;
m_MyAudioSource.Stop();
}
for more information u can check https://docs.unity3d.com/ScriptReference/AudioSource.Stop.html
I had to use gameObject.GetComponent().isOn ins$$anonymous$$d of toggle.isOn, but it worked! Thank you so much!
Follow this Question
Related Questions
C# On Click sound to play before loading scene 0 Answers
Cracking at end of audio? 0 Answers
Link to Instagram/web from mobile ot working 0 Answers
Playing a sound on all button presses? 1 Answer
How to stop and re-start audio? 1 Answer