Home > front end >  Script stopped changing value
Script stopped changing value

Time:09-17

I'm trying to make toggle music on and off script and for some reason the value isnt changing what am i doing wrong ?

[SerializeField] Toggle toggle;
[SerializeField] AudioSource audioSource;
public int Music;

private void Update()
{
    Music = PlayerPrefs.GetInt("Music");
    if (Music == 0) audioSource.enabled = false;
    else if (Music == 1) audioSource.enabled = true;
    PlayerPrefs.SetInt("Music", Music);
    MakeTextRed();
}
public void MakeTextRed()
{
    if (toggle.isOn == true) Music = 1;
    else if (toggle.isOn == false) Music = 0;
}

When I play the game and click on the toggle button the Music value doesn't change in the inspector.

CodePudding user response:

I'm not sure about your code whether it's wrong or true. You can use this simple code instead of int or others

 [SerializeField] Toggle toggle;
 [SerializeField] AudioSource audioSource;
 
 private void Update(){
    // CheckToggler();
    // More Simple One is
    audioSource.enabled = toggle.isOn;
 }
 private void CheckToggler(){
    if (toggle.isOn) // On
      audioSource.enabled = true;
   else //off
     audioSource.enabled = false;
 }

CodePudding user response:

Your logic is incorrect, that's why. Common practice is starting a debug session with Visual Studio. It will show a value you are trying to set.

private void Update()
{
    Music = PlayerPrefs.GetInt("Music"); // Read value from Prefs
    if (Music == 0) audioSource.enabled = false;
    else if (Music == 1) audioSource.enabled = true;
    PlayerPrefs.SetInt("Music", Music); // Set value to Prefs (It's the same)
    MakeTextRed(); // This must be one line higher
}
  • Related