Problem With Saving My Toggle's State.

4420642--403129--2.png Hello, I am able to save the state of my toggle through PlayerPrefs succesfully but there is a bug.
Whenever I start the game with my PlayerPrefs int value at = 0…
It sets it to = 0 at first in the Debug and my game is kept muted…
But it sets it to = 1 directly afterwards.

I have found that the Toggle.isON part of my script causes this, I will provide code and Debug screenshots below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using UnityEngine.SceneManagement;

public class SettingsUIManager : MonoBehaviour
{
    [SerializeField] private AudioSource musicSource;
    [SerializeField] private GameObject musicButton;

    public int musicBool;
 


    void Start()
    {
        GetInt();
        PlayMusic();
     
        if (musicBool == 0)
        {
            musicButton.GetComponent<Toggle>().isOn = false;
        }
        else
        {
            musicButton.GetComponent<Toggle>().isOn = true;
        }
    }

    public void ToggleMusic()
    {
        if (PlayerPrefs.GetInt("Music") == 0)
        {
            musicSource.mute = !musicSource.mute;

            musicBool = 1;

            PlayerPrefs.SetInt("Music", musicBool);
            Debug.Log("musicBool: " + musicBool);
        }
        else if (PlayerPrefs.GetInt("Music") == 1)
        {
            musicSource.mute = !musicSource.mute;

            musicBool = 0;

            PlayerPrefs.SetInt("Music", musicBool);
            Debug.Log("musicBool: " + musicBool);
        }
    }

    public void GetInt()
    {
        musicBool = PlayerPrefs.GetInt("Music");
        Debug.Log("musicBool: " + musicBool);
    }

    public void PlayMusic()
    {
        if (musicBool == 1)
        {
            musicSource.Play();
        }
        else
        {
            Debug.Log("Can't play music");
        }
    }
}

4420642--403126--1.png

Setting the Toggle isOn value invokes the event callback and your ToggleMusic function flips the values regardless of what the actual toggle’s value is. You should compare it, before setting your values.

public void ToggleMusic()
{
     if(toggle.isOn == true)
     {
           // set on values
     }
     else
     {
         // set off values
     }
}
1 Like

Toggle buttons can´t be changed unless you access throw his component or assign it in inspector

public Toggle toggle_fx; //assign in inspector
private void Load ()
{
       bool isOn = Convert.ToBoolean(PlayerPrefs.GetInt("fx"));
       toogle_fx.isOn = isOn;

}