Search Unity

PlayerPrefs | Getting around no BOOLEAN setting

Discussion in 'Scripting' started by iEarthHero1, Apr 3, 2010.

  1. iEarthHero1

    iEarthHero1

    Joined:
    Jul 28, 2009
    Posts:
    301
    OnGUI allows for toggles using a boolean.

    However, PlayerPrefs has no SetBool.

    I have been using SetInt to get around this... but this requires several lines of code.

    Is there an elegant solution to storing a boolean through PlayPrefs?

    Thanks.
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
  3. iEarthHero1

    iEarthHero1

    Joined:
    Jul 28, 2009
    Posts:
    301
    Thanks Eric.

    This is exactly what I was looking for when I used the word "elegant".

    As an added bonus I had forgotten about the ability to use "value?1:0" format (also being elegant).

    For quick reading below:

    Code (csharp):
    1. static function  SetBool (name : String, value : boolean) {
    2.  
    3.     PlayerPrefs.SetInt(name, value?1:0);
    4. }
    5.  
    6. static function GetBool (name : String) : boolean {
    7.     return PlayerPrefs.GetInt(name)==1?true:false;
    8. }
    9.  
    10. static function GetBool (name : String, defaultValue : boolean) : boolean {
    11.     if (PlayerPrefs.HasKey(name)) {
    12.         return GetBool(name);
    13.     }
    14.     return defaultValue;
    15. }
    Thanks.
     
    Ash-Blue likes this.
  4. LimeSplice

    LimeSplice

    Joined:
    Jul 15, 2011
    Posts:
    111
    Hi
    I'm trying to use the above script. But when I use SetBool, and I check in my playerprefs.plist file, the 'Type' is listed as a String not a Boolean.

    This is what I'm using to set the pref:

    PlayerPrefsX.SetBool("Hints", true);

    Something I'm doing wrong?
     
  5. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    there is no inbuilt support to write bool, a fake can not change that as a fake can not change the engine code

    I don't even think it writes anything but strings actually (as above code actually writes int, not string yet if you see string it potentially saves string independent of what comes in)
     
  6. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Nothing is wrong; the type in the .plist file is irrelevant.

    --Eric
     
    Mycroft likes this.
  7. CoCoNutti

    CoCoNutti

    Joined:
    Nov 30, 2009
    Posts:
    513
    Can I ask why SetBool isn't supported? Just curious.
     
    TooManySugar likes this.
  8. thesfid

    thesfid

    Joined:
    Oct 19, 2010
    Posts:
    12
    This is a fantastic workaround. Thank you for sharing.
    Any idea if booleans are supported in PlayerPrefs in Unity 4.x?
     
  9. EliteMossy

    EliteMossy

    Joined:
    Dec 2, 2012
    Posts:
    513
    Not that i am aware, i simply wrote a playerprefs extension