module-navigation-tool/Editor/Toolbar/Settings/ToolbarProjectSettings.cs

113 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace Module.NavigationTool.Editor.Toolbar
{
[Serializable]
public sealed class ToolbarProjectSettings
{
[SerializeField]
private List<string> keys = new();
[SerializeField]
private List<string> values = new();
public const string RELATIVE_PATH = "ProjectSettings/ToolbarProjectSettings.asset";
public void Load()
{
try
{
string path = GetAbsolutePath();
if (File.Exists(path))
{
string json = File.ReadAllText(path);
JsonUtility.FromJsonOverwrite(json, this);
}
else
{
keys.Clear();
values.Clear();
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
public void Save()
{
try
{
string path = GetAbsolutePath();
string json = JsonUtility.ToJson(this, true);
File.WriteAllText(path, json, Encoding.Unicode);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
public T GetValueAs<T>() where T : new()
{
try
{
string key = typeof(T).FullName;
int index = keys.IndexOf(key);
if (index == -1)
{
var t = new T();
keys.Add(key);
values.Add(JsonUtility.ToJson(t));
return t;
}
string json = values[index];
return JsonUtility.FromJson<T>(json);
}
catch (Exception e)
{
Debug.LogException(e);
return new T();
}
}
public void SetValue<T>(T value) where T : new()
{
try
{
string key = typeof(T).FullName;
string json = JsonUtility.ToJson(value);
int index = keys.IndexOf(key);
if (index != -1)
{
values[index] = json;
}
else
{
keys.Add(key);
values.Add(json);
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
private string GetAbsolutePath()
{
string path = Application.dataPath;
path = path.Substring(0, Application.dataPath.Length - 6);
path += RELATIVE_PATH;
return path;
}
}
}