Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

player prefs using toggles

Discussion in 'Scripting' started by plusplusgames, Oct 31, 2021.

  1. plusplusgames

    plusplusgames

    Joined:
    Jul 26, 2021
    Posts:
    64
    here I have a toggle when I press it the music turns off and when i press it again it turns back on using player prefs I want to make my game remember if it was of or on my main problem is "cannot convert bool to string.

    Code (CSharp):
    1.  public bool MusicToggles;
    Code (CSharp):
    1.    
    2. public void MusicToggle(bool muted2)
    3.     {
    4.         if (muted2)
    5.         {
    6.             GameObject.FindWithTag("Music").GetComponent<AudioSource>().mute = true;
    7.  
    8.             PlayerPrefs.SetString("Muted", muted2);
    9.         }
    10.         else
    11.         {
    12.             GameObject.FindWithTag("Music").GetComponent<AudioSource>().mute = false;
    13.             PlayerPrefs.SetString("NotMuted", muted2);
    14.         }
    15.     }
     
  2. ubbelito

    ubbelito

    Joined:
    Sep 24, 2018
    Posts:
    23
    There are many potential solutions, but converting bool to string or int is perhaps easiest done with the ternary operator.
    Code (csharp):
    1. PlayerPrefs.SetInt("Muted", audioSource.mute ? 1 : 0);
    However, when you decode you instead must check
    Code (csharp):
    1. bool isMuted = PlayerPrefs.GetInt("Muted") != 0;
    I am not sure if you could make your original solution work even if you solved the converison. Since you set both Muted and NotMuted at some point you will notice that both are set, and then it will be hard to know what the correct setting is.
     
  3. plusplusgames

    plusplusgames

    Joined:
    Jul 26, 2021
    Posts:
    64
    do you think changing them both to be either "muted" or "notmuted" is a good idea
     
  4. ubbelito

    ubbelito

    Joined:
    Sep 24, 2018
    Posts:
    23
    I would use ”muted” as the only option. That seems easiest.
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    You should not splatter string literals all over your program, such as "Muted" and "NotMuted".

    For one it makes a colossal mess of your code, for two it is dangerous if you mistype one, or if one gets changed and the others don't.

    Instead, centralize it with a simple wrapper class like this and use the property only:

    Here's an example of simple persistent loading/saving values using PlayerPrefs:

    https://gist.github.com/kurtdekker/01da815d2dfd336a925ae38019c3a163

    Useful for a relatively small number of simple values.

    It even shows a wrapped example of precisely what @ulfh suggests above.