Saveables

Open World - Scripts - Saveables

How to Serialize and Deserialize an Object in Unity3D with C#

To Serialize and Deserialize an Object unity has made this really simple by using the JsonUtility class. So now once a class has the Serializable Attribute it's just a case of calling JsonUtility ToJson and pass in an object to serialize.

public static void SaveExperience(this Experience exp) => File.WriteAllText(ExperienceJsonPath, JsonUtility.ToJson(exp));

Now to deserialize the data back you just need to call JsonUtility FromJson give it the tpye and the json string.

public static Experience LoadExp() => File.Exists(ExperienceJsonPath) ? JsonUtility.FromJson<Experience>(File.ReadAllText(ExperienceJsonPath)) : new Experience();

Saveables.cs 1.2KB

Collectable 457B

Collectables 4.6KB

Experience 1KB

Global Static Data 799B


using System.IO;
using UnityEngine;
using static Collectables;

static class Saveables
{
    #region Collectables
    public static string CollectablesJsonPath => $"{GlobalStaticData.DocumentsDirWithAppName}/PlayerCollectables";
    public static CollectableList LoadCollectables(CollectableTypes collectableType) => File.Exists($"{CollectablesJsonPath}{collectableType}.json") ?
        JsonUtility.FromJson<CollectableList>(File.ReadAllText($"{CollectablesJsonPath}{collectableType}.json")) : new CollectableList(collectableType);

    public static void SaveCollectables(this CollectableList collectables) => File.WriteAllText($"{CollectablesJsonPath}{collectables.collectableType}.json", JsonUtility.ToJson(collectables));

    #endregion
    #region Experience   
    public static string ExperienceJsonPath => $"{GlobalStaticData.DocumentsDirWithAppName}/PlayerExp.json";
    public static Experience LoadExp() => File.Exists(ExperienceJsonPath) ? JsonUtility.FromJson<Experience>(File.ReadAllText(ExperienceJsonPath)) : new Experience();
    public static void SaveExperience(this Experience exp) => File.WriteAllText(ExperienceJsonPath, JsonUtility.ToJson(exp));
    #endregion
}
Powered by w3.css