I’m making an inventory asset for my game Voidkeeper( and to possibly sell on the asset store), and I’m running into a hitch saving bool arrays.
I know I can use ArrayPrefs2, but as I’m also learning a lot from the things I want to implement for uses in other functionality, I’d like help stepping through converting my bool array “equippedBools” to be serialized by binaryformatter, so bear with me.
I came across this example for a single bool:
PlayerPrefs.SetInt(Convert.ToInt32(someBool));
Now I’m trying to understand how to do it for an entire array, using binaryformatter.
(Mike Talbot, aka Whydoit, if you read this, know I thoroughly enjoyed your UnityGems Tutorial covering this subject.).![]()
Here’s a code snippet from my script where I am using a proxy bool array to set values in my Items class, which works btw, just need to save and load the bool array, rather than save my items class so I can keep their texture2D, and game objects intact.:
(I need the method to save and load for the bool array, as the snippet only shows an attempt for the item class.)
public List<Items> itemsInGame = new List<Items>();
private int itemInGameCount = 0;
public bool[] equippedBools = new bool[]{};
// Use this for initialization
void Start() {
//Clear equipment list.
equippedList.Clear ();
itemInGameCount = itemsInGame.Count;
equippedBools = new bool[itemInGameCount];
//Get the data
var data = PlayerPrefs.GetString("EquipmentBools");
// //If not blank then load it
if(!string.IsNullOrEmpty(data))
{
//Binary formatter for loading back
var b = new BinaryFormatter();
//Create a memory stream with the data
var m = new MemoryStream(Convert.FromBase64String(data));
//Load back the equipped values in all the Items in game.
for(int t = 0; t < itemsInGame.Count; t++){
itemsInGame[t].equipped = b.Deserialize(m);
}
}
foreach(Items n in itemsInGame){
if(n.equipped == true){
equippedList.Add (n);
}
}
for(int t = 0; t < itemsInGame.Count; t++){
equippedBools[t] = itemsInGame[t].equipped;
}
foreach (bool value in equippedBools)
{
Debug.Log(""+ value);
}
void SaveEquipment () {
//Get a binary formatter
var b = new BinaryFormatter();
//Create an in memory stream
var m = new MemoryStream();
//Save the equipment in equippedlist.
b.Serialize(m, itemsInGame);
//Add it to player prefs
PlayerPrefs.SetString("EquipmentList", Convert.ToBase64String(m.GetBuffer()));
}
Thanks for your time.