Alright so the problem is: You have referenced the ToggleMusic method from this instance of Music in your toggle .. then you change scenes and come back .. but due to the singleton thing you destroy the Music instance linked to this new Toggle -> Toggle does nothing now.
You already have a singleton pattern so why not directly make use of it:
public class Music : MonoBehaviour
{
private static Music _singleton;
public static Music Singleton => _singleton;
[SerializeField] private AudioSource audioSource;
private bool volumeOn;
public bool MusicIsOn => volumeOn;
private void Awake()
{
if (_singleton)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
_singleton = this;
if(!audioSource) audioSource = GetComponent<AudioSource>();
ToggleMusic(true);
}
public void ToggleMusic(bool on)
{
audioSource.volume = on ? 1f : 0f;
volumeOn = on;
}
public void ToggleMusic()
{
ToggleMusic(!volumeOn);
}
}
And then on your toggle instead of assigning a callback via the Inspector rather do
public class MusicToggle : MonoBehaviour
{
[SerializeField] private Toggle toggle;
private void Awake ()
{
if(!toggle) toggle = GetComponent<Toggle>();
toggle.onValueChanged.AddListener(OnValueChanged);
toggle.isOn = Music.Singleton.MusicIsOn;
}
private void OnValueChanged (bool on)
{
Music.Singleton.ToggleMusic(on);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…