Save & Load Data Securely Using BinaryFormatter


PlayerData.cs
1
2
3
4
5
6
7
8
//Container to hold data
[System.Serializable]
public class PlayerData
{
    public string playerName;
    public float playerAge;
    public int playerClass;
}

SaveLoadSystem.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.UI;
 
public class SaveLoadSystem : MonoBehaviour
{
    public InputField nameInputField;
    public Slider ageSlider;
    public Dropdown classDropdown;
 
    //Path where data file will be stored
    string filePath;
 
    void Awake()
    {
        filePath = Path.Combine(Application.dataPath, "playerData.dat");
    }
 
    public void SavePlayerData()
    {
        PlayerData playerData = new PlayerData();
        playerData.playerName = nameInputField.text;
        playerData.playerAge = ageSlider.value;
        playerData.playerClass = classDropdown.value;
 
        Stream stream = new FileStream(filePath, FileMode.Create);
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(stream, playerData);
        stream.Close();
    }
 
    public void LoadPlayerData()
    {
        if(File.Exists(filePath))
        {
            Stream stream = new FileStream(filePath, FileMode.Open);
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            PlayerData data = (PlayerData)binaryFormatter.Deserialize(stream);
            stream.Close();
 
            nameInputField.text = data.playerName;
            ageSlider.value = data.playerAge;
            classDropdown.value = data.playerClass;
        }
    }
}