How to add a new string in a list of strings AND serialize the list everytime a new string is added to the list?
So basically I want the add a new string to a list every time my player achieve a score and be able to save it. So when the player turn the game back on, the new string is still in the list.
.
(The strings in the list is the name on levels, so every time I am adding a new string, I am adding a new level). In case you want to know what the strings does.
Answer by dasani2406 · Sep 05, 2017 at 09:48 PM
Hey Everyone who followed this Question .... I think I got the ANSWER.....
THAT IS MY SCRIPTS.... when I want to save it ( you guys can change the condition when you want to save it).
if (Input.GetKeyDown(KeyCode.Q) )
{
if (!ScoreManager.GetInstance(). Levelnames.Contains("levels"))
{
ScoreManager.GetInstance().Levelnames.Add("levels");
}
else
{
return;
}
ScoreManager.GetInstance().Save();
}
if (Input.GetKeyDown(KeyCode.E))
{
if (!ScoreManager.GetInstance().Levelnames.Contains("Main Menu"))
{
ScoreManager.GetInstance().Levelnames.Add("Main Menu");
}
else
{
return;
}
ScoreManager.GetInstance().Save();
}
the Saving and loading scripts( the scripts is a dontdestroyOn because of my particular game. That is why you have ScoreManager.GetInstance. save(); in the above script, because I am calling the save method from the below script.)
public List<string> Levelnames = new List<string>();
public void Save()
{
BinaryFormatter BF = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/PlayerInfo.dat");
PlayerData data = new PlayerData();
data.NewLevelnames = Levelnames;
BF.Serialize(file, data);
file.Close();
}
public void load()
{
if (File.Exists(Application.persistentDataPath + "/PlayerInfo.dat"))
{
BinaryFormatter BF = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/PLayerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)BF.Deserialize(file);
file.Close();
Levelnames = data.NewLevelnames;
}
}
}
[Serializable]
class PlayerData
{
public List<string> NewLevelnames = new List<string>();
}
Hope it help..... Peace out.. :)