- Home /
Sound effects also turned off when switching off music
My toggle button for music is working well. However, it turns off sound effects as well. I want to toggle for both music and sound effects separately. I don't understand where it's gone wrong. Here's my code for the music toggle:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MusicToggle : MonoBehaviour
{
private Music music;
public Button musicToggleButton;
public Sprite musicOnSprite;
public Sprite musicOffSprite;
void Start()
{
music = GameObject.FindObjectOfType<Music>();
UpdateIcon();
}
public void PauseMusic()
{
music.ToggleMusic();
UpdateIcon();
}
void UpdateIcon()
{
if (PlayerPrefs.GetInt("Muted", 0) == 0)
{
AudioListener.volume = 1;
musicToggleButton.GetComponent<Image>().sprite = musicOnSprite;
}
else
{
AudioListener.volume = 0;
musicToggleButton.GetComponent<Image>().sprite = musicOffSprite;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class $$anonymous$$usic : $$anonymous$$onoBehaviour
{
static $$anonymous$$usic Instance = null;
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
}
else
{
Instance = this;
GameObject.DontDestroyOnLoad(this);
}
}
public void Toggle$$anonymous$$usic()
{
if(PlayerPrefs.GetInt("$$anonymous$$uted", 0) == 0)
{
PlayerPrefs.SetInt("$$anonymous$$uted", 1);
//AudioListener.volume = 1;
}
else
{
PlayerPrefs.SetInt("$$anonymous$$uted", 0);
//AudioListener.volume = 0;
}
}
}
Answer by UnderShad · Jun 07, 2020 at 12:50 AM
The problem is the AudioListener.volume = 0; AudioListener is like a ear and if you turn ears to zero then no sound will be heard. Use AudioSource.volume=0; Instead
@UnderShad I got this error now. How can i fix this ?
Error CS0120 An object reference is required for the non-static field, method, or property 'AudioSource.volume'
And another thing is that, my playerpref for the toggle value can be loaded upon launching the application. However, since I place my toggle button on the settings panel in the main menu. It is only loaded when i click on the settings button everytime i enter the application.