BITKit/Packages/Runtime~/Unity/Scripts/Config/ConfigSO.cs

49 lines
1.6 KiB
C#

using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace BITKit
{
public static partial class Utility
{
public static partial class Config
{
public static bool TryGetConfig<T>(string configName, out T value)
{
var path = Utility.Path.CombinePath(Utility.Path.persistentDataPath, $"{configName}.json");
if (File.Exists(path))
{
var json = File.ReadAllText(path);
value = JsonConvert.DeserializeObject<T>(json);
return true;
}
value = default;
return false;
}
public static T GetConfig<T>(string configName) where T : new()
{
if (TryGetConfig<T>(configName, out var config))
{
}
else
{
SaveConfig<T>(configName, new());
TryGetConfig<T>(configName, out config);
}
return config;
}
public static void SaveConfig<T>(string configName, T value)
{
var json = JsonConvert.SerializeObject(value, Formatting.Indented);
var path = Utility.Path.CombinePath(Utility.Path.persistentDataPath, $"{configName}.json");
File.WriteAllText(path, json);
}
}
}
public class ConfigSO : ScriptableObject
{
public string json;
}
}