- Home /
Saving Data (closed)
Hi ! Ik have a drinks class with 2 variables in it : string drinkName, float drinkPrice; Each value is filled in by InputFields and then gets saved in a Drinks list. All working so no problem there. However I wish to add drinks to this list without losing the progress each time I shut down my application.
I'm aware of the playerprefs method to save data but are there other ways to do so ? Perhaps better ways I could look into?
Thanks in advance
Answer by Halichoerus · Oct 18, 2015 at 09:13 AM
You can use data serialization and write/read your data to a file, I've recently added save/load for game options and progress and it was pretty easy. I would recommend this tutorial by unity, it explains the basics and gives you a working example you can recreate with little knowledge on the subject. Just skip ahead a bit to get past the player prefabs part.
Great thing about doing it this way is you just create your own data class which can contain any serializable data type, which is quite a few. Here's an edited snippet from my project, it's basically just the example from the tutorial I linked.
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class DataSaver : MonoBehaviour {
public void SaveData() {
MyData data = new Data();
// add relevent data to my new data object e.g
data.exampleInt = 5;
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/SomeData");
bf.Serialize(file, data);
file.Close();
}
public void LoadData() {
if (File.Exists(Application.persistentDataPath + "/SomeData")) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/PlayerOptions", FileMode.Open);
OptionsData data = (OptionsData)bf.Deserialize(file);
file.Close();
// Do stuff with loaded data eg
var someNewInt = data.exampleInt;
}
}
}
[Serializable]
class MyData {
// Any serializable data types you want to save/load e.g
public int exampleInt;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612041719im_/https://answers.unity.com/themes/thub/images/avi.jpg)