WXMC/.svn/pristine/87/878b729683de560166b0c9e6cfcdf3f732ebf43b.svn-base
2024-12-04 16:18:46 +08:00

137 lines
2.8 KiB
Plaintext

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[System.Serializable]
public class PHomeTable<T> : IEnumerable<KeyValuePair<string, T>>
{
public TextAsset FromAsset;
private Dictionary<string, T> m_datas;
public T this[string id]
{
get
{
if (m_datas == null)
{
return default;
}
return m_datas[id];
}
}
public bool TryGet(string key, out T data)
{
return m_datas.TryGetValue(key, out data);
}
public int Count
{
get
{
return m_datas.Count;
}
}
public void EnsureLoad(CommonSerializing.SerializeSetting settings)
{
if (m_datas != null)
{
return;
}
var deserializer = new CommonSerializing.Deserializer();
deserializer.Settings = settings;
var bytes = FromAsset.bytes;
var dataProvider = CommonSerializeDefine.CellDataProvider.FromBytes(bytes);
m_datas = deserializer.DeserializeMap<T>(dataProvider);
}
public void EnsureLoad(IEnumerable<KeyValuePair<string, T>> datas)
{
if (m_datas != null)
{
return;
}
m_datas = new Dictionary<string, T>(datas);
}
public IEnumerable<string> Keys
{
get
{
if (m_datas == null)
{
yield break;
}
foreach (var item in m_datas)
{
yield return item.Key;
}
}
}
public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
{
if (m_datas == null)
{
yield break;
}
foreach (var item in m_datas)
{
yield return item;
}
}
public KeyValuePair<string, T>? GetRandomOne()
{
if (m_datas == null || m_datas.Count == 0)
{
return null;
}
int count = m_datas.Count;
float prop = 1.0f / (float)count;
float stop = UnityEngine.Random.Range(0.0f, 1.0f);
float total = 0;
foreach (var item in m_datas)
{
total += prop;
if (total > stop)
{
return item;
}
}
return null;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new System.NotImplementedException();
}
}
public class PHomeTables : MonoBehaviour
{
public static PHomeTables main;
public PHomeTable<PHomeParagraph> Paragraphs;
private void Awake()
{
main = this;
CommonSerializing.SerializeSetting loadSettings = UnitySerializer.Settings;
Paragraphs.EnsureLoad(loadSettings);
DontDestroyOnLoad(gameObject);
}
}