Inspector面板上不能序列化字典很不方便,于是自己写了一个
- 因为是只用于在Inspector上配置使用,而且也为了避免代码中修改,就没有实现写的方法(有需要的可以扩展)
- 这里我用空间换取便捷(List和Dictionary存了两边数据),根据需要可以修改用时间换取便捷(不定义Dictionary,查找时循环list)
- Lazy是用于当尝试被访问时才执行的,这样避免使用时还需要调一边Init函数,具体可以找直接百度,别的大佬写的很详细
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Encoding:UTF-8
[Serializable]
public class SerializableDictionary<K, V> : IEnumerable
{
[Serializable]
public struct Ele
{
public K key;
public V value;
}
[SerializeField]
private List<Ele> list = new List<Ele>();
private Lazy<Dictionary<K, V>> dic;
SerializableDictionary()
{
dic = new Lazy<Dictionary<K, V>>(Init);
}
public Dictionary<K, V> Init()
{
Dictionary<K, V> dictionary = new Dictionary<K, V>(list.Count);
for (int i = 0; i < list.Count; ++i)
dictionary.Add(list[i].key, list[i].value);
return dictionary;
}
public V this[K key] { get => dic.Value[key]; }
public int Count => dic.Value.Count;
public bool ContainsKey(K key)
{
return dic.Value.ContainsKey(key);
}
public bool TryGetValue(K key, out V value)
{
return dic.Value.TryGetValue(key, out value);
}
public IEnumerator GetEnumerator()
{
return dic.Value.GetEnumerator();
}
}
前人栽树后人乘凉,乘凉之后也要记得栽树哦。