Player prefs and bool

I'm having a hard time figuring out how to use player prefs to save and load the game(automatic at game start) in c#.

It doesn't help that most of the things that should be saved are of the bool type, and it only seems to take int and strings, do I really have to convert all my bools if so, what would be the cleanest way to do that?

So how would one go saving and loading bool types?

You can use BoolPrefs (still uses GetInt/SetInt, but you don't have to think about it).

Just convert to string:

bool tempbool = true;
PlayerPrefs.SetString("testBool", tempbool.ToString());
tempbool = Boolean.Parse(PlayerPrefs.GetString("testBool", "true"));

Bool is nothing more than yes or no, true or false, something or zero… So, considering a simple C program… I usually use 2 methods to access 1 attribute.

Example:

public class User{

	private string FIELD_PREMIUM = "premiumAccount";
	private bool premiumAccount;

	public User(){
		this.LoadUser();
	}

	public void LoadUser(){
		this.premiumAccount = PlayerPrefs.GetInt(FIELD_PREMIUM,0)>0?true:false;
	}

	public void PremiumAccountPurchased(){
		this.premiumAccount = true;
		this.Save();
	}

	public bool HasPremiumAccount(){
		this.LoadUser();
		return this.premiumAccount;
	}

	public void Save(){
		PlayerPrefs.SetInt(FIELD_PREMIUM, this.premiumAccount?1:0);
	}
}

All that you need is:

To get the value:
bool value = PlayerPrefs.GetInt(“somefield”,0)>0?true:false;

To set the value:
PlayerPrefs.SetInt(“somefield”, myBoolValue?1:0);

I hope this helps your or someone :slight_smile:

Or you can create this extension:

using UnityEngine;
using System.Collections;

public static class PlayerPrefExtension
{
	public static bool GetBool (this PlayerPrefs playerPrefs, string key)
	{
		return PlayerPrefs.GetInt (key) == 1;
	}

	public static void SetBool (this PlayerPrefs playerPrefs, string key, bool state)
	{
		PlayerPrefs.SetInt (key, state ? 1 : 0);
	}
}

“Get” by using this line:
bool myBool = PlayerPrefs.GetInt (“VariableName”) == 1 ? true : false;

“Set” by using this line:
PlayerPrefs.SetInt (“VariableName”, true ? 1 : 0);

Writing:

bool val = true;
PlayerPrefs.SetInt("PropName", val ? 1 : 0);
PlayerPrefs.Save();

Reading:

bool val = PlayerPrefs.GetInt("PropName") == 1 ? true : false;