41 lines
1.1 KiB
C#
41 lines
1.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public interface ILoader<T>
|
|
{
|
|
List<T> GetList();
|
|
}
|
|
|
|
public class DataManager : IManager
|
|
{
|
|
private Dictionary<string, object> _cache = new Dictionary<string, object>();
|
|
|
|
public Dictionary<TKey, TValue> LoadToDict<TLoader, TKey, TValue>(string path, System.Func<TValue, TKey> keySelector) where TLoader : ILoader<TValue>
|
|
{
|
|
if (_cache.TryGetValue(path, out object cachedDict)) return (Dictionary<TKey, TValue>)cachedDict;
|
|
|
|
List<TValue> list = LoadJson<TLoader, TValue>(path);
|
|
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
|
|
foreach (TValue item in list)
|
|
{
|
|
dict.Add(keySelector(item), item);
|
|
}
|
|
|
|
_cache.Add(path, dict);
|
|
return dict;
|
|
}
|
|
|
|
private List<T> LoadJson<TLoader, T>(string path) where TLoader : ILoader<T>
|
|
{
|
|
TextAsset textAsset = Manager.Resource.Load<TextAsset>($"{path}");
|
|
TLoader data = JsonUtility.FromJson<TLoader>(textAsset.text);
|
|
return data.GetList();
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
_cache.Clear();
|
|
}
|
|
}
|