using System;
using System.IO;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace com.zibra.liquid.Plugins
{
///
/// Package Scriptable Settings singleton pattern implementation.
///
public abstract class PackageScriptableSettingsSingleton : PackageScriptableSettings
where T : PackageScriptableSettings
{
static T s_Instance;
///
/// Returns a singleton class instance
/// If current instance is not assigned it will try to find an object of the instance type,
/// in case instance already exists in a project. If not, new instance will be created,
/// and saved under a location
///
public static T Instance
{
get {
if (s_Instance == null)
{
s_Instance = Resources.Load(typeof(T).Name) as T;
if (s_Instance == null)
{
s_Instance = CreateInstance();
SaveToAssetDatabase(s_Instance);
}
}
return s_Instance;
}
}
///
/// Saves instance to an editor database.
/// Only applicable while in the editor.
///
public static void Save()
{
// Only applicable while in the editor.
#if UNITY_EDITOR
// TODO use Undo
EditorUtility.SetDirty(Instance);
#endif
}
///
/// // Only applicable while in the editor.
///
static void SaveToAssetDatabase(T asset)
{
// Only applicable while in the editor.
#if UNITY_EDITOR
var path = Path.Combine(asset.SettingsFilePath);
var directory = Path.GetDirectoryName(path);
if (directory == null)
throw new InvalidOperationException($"Failed to get directory from package settings path: {path}");
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
AssetDatabase.CreateAsset(asset, path);
#endif
}
}
}