Unity 3D: Save Game Data to a File, Load Game Data From a File

3/6/2020 5:37:17 PM

The following code will allow you to save game data to a file in json format and load that data from a json file.


//this is the model that holds your game data
using System;

namespace MyProject.Models
{
    [Serializable]
    public class Game_Data
    {
        public int Coins = 0;
        public int Hearts = 0;        
        public int Gems = 0;			
    }
}


			
			
//this class will save your model to a file or load it from a file
using System;
using System.IO;
using UnityEngine;

namespace MyProject
{
    public class Data
    {                
        public static Models.Game_Data Load_Game_Data()
        {
            string folder_path = (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer ? Application.persistentDataPath : Application.dataPath);            
            string file_name = "game_data.json";
            string file_path = folder_path + "/" + file_name;


            try
            {
                var json_data = File.ReadAllText(file_path);
                var game_data = JsonUtility.FromJson(json_data);
				
				return game_data;
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
            
            
            return null;
        }


        public static bool Save_Game_Data(Models.Game_Data game_data)
        {
            string folder_path = (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer ? Application.persistentDataPath : Application.dataPath);            
            string file_name = "game_data.json";
            string file_path = folder_path + "/" + file_name;
            
			
            try
            {
                string json_data = JsonUtility.ToJson(game_data);
                File.WriteAllText(file_path, json_data);
				
				return true;
            }            
            catch (Exception ex)
            {
                Debug.LogError(ex);                
            }            


            return false;
        }        
    }
}