using System.Collections; using System.Collections.Generic; using UnityEngine; public class MuteToggle : MonoBehaviour { [Header("References")] public ImageToggle toggle; public AudioSource audioSource; private const string MUTE_PREF_KEY = "muted"; void Start() { // Always read from PlayerPrefs to ensure consistency across scene changes bool isMuted = GetMutedState(); // Set the audio source mute state if (audioSource != null) { audioSource.mute = isMuted; } // Set the toggle visual state to match the saved state if (toggle != null) { // Set toggle state without triggering the event (we'll sync it manually) toggle.isOn = !isMuted; // isOn means sound is ON, so !isMuted toggle.onToggle.AddListener(OnToggleChanged); } Debug.Log($"MuteToggle initialized - Muted: {isMuted}"); } void OnToggleChanged(bool isOn) { // isOn means sound is ON, so muted = !isOn bool shouldMute = !isOn; // Update audio source if (audioSource != null) { audioSource.mute = shouldMute; } // Save to PlayerPrefs SetMutedState(shouldMute); Debug.Log($"Mute state changed - Muted: {shouldMute}"); } bool GetMutedState() { // Returns true if muted, false if not muted // Default to false (not muted) if key doesn't exist return PlayerPrefs.GetInt(MUTE_PREF_KEY, 0) == 1; } void SetMutedState(bool muted) { PlayerPrefs.SetInt(MUTE_PREF_KEY, muted ? 1 : 0); PlayerPrefs.Save(); } void OnDestroy() { // Clean up listener to prevent memory leaks if (toggle != null) { toggle.onToggle.RemoveListener(OnToggleChanged); } } }