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");
}
}
}