Saving and loading your game in Unity is not hard at all if you know the right way to do it. When you use binary serialization in C# you have already won half of the battle.

 

GameData.cs

using UnityEngine;
using UnityEngine.UI;

public class GameData : MonoBehaviour {

	public int GameInteger { get; set; }
    public string GameString { get; set; }

    [SerializeField]
    private Text textInteger;
    [SerializeField]
    private Text textString;

    public void GenerateNewData()
    {
        GameInteger = Random.Range(1, 1000);
        GameString = System.Convert.ToBase64String(System.BitConverter.GetBytes(GameInteger));
        ShowData();
    }

    public void ShowData()
    {
        textInteger.text = GameInteger.ToString();
        textString.text = GameString;
    }
}

 

SaveScript.cs

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

[RequireComponent(typeof(GameData))]
public class SaveScript : MonoBehaviour {

    private GameData gameData;
    private string savePath;

	void Start () 
	{
        gameData = GetComponent<GameData>();
        savePath = Application.persistentDataPath + "/gamesave.save";
	}
	
	public void SaveData()
    {
        var save = new Save()
        {
            SavedInteger = gameData.GameInteger,
            SavedString = gameData.GameString
        };

        var binaryFormatter = new BinaryFormatter();
        using (var fileStream = File.Create(savePath))
        {
            binaryFormatter.Serialize(fileStream, save);
        }

        Debug.Log("Data Saved");
    }

    public void LoadData()
    {
        if (File.Exists(savePath))
        {
            Save save;

            var binaryFormatter = new BinaryFormatter();
            using (var fileStream = File.Open(savePath, FileMode.Open))
            {
                save = (Save)binaryFormatter.Deserialize(fileStream);
            }

            gameData.GameInteger = save.SavedInteger;
            gameData.GameString = save.SavedString;
            gameData.ShowData();

            Debug.Log("Data Loaded");
        }
        else
        {
            Debug.LogWarning("Save file doesn't exist.");
        }
    }
}

 

Save.cs

using UnityEngine;

[System.Serializable]
public class Save {
    public int SavedInteger;
    public string SavedString;
}

 

About the author 

Matt Rešetár

Matt is an app developer with a knack for teaching others. Working as a freelancer and most importantly developer educator, he is set on helping other people succeed in their Flutter app development career.

You may also like

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >