欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity中序列化问题

程序员文章站 2022-03-02 11:48:30
...

prefab序列化保存Dictionary

先上一个序列化Dic的解决办法,后续更新

[System.Serializable]
    public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
    {
        [SerializeField]
        private List<TKey> _keys = new List<TKey>();
        [SerializeField]
        private List<TValue> _values = new List<TValue>();

        public void OnBeforeSerialize()
        {
            this._keys.Clear();
            this._values.Clear();
            this._keys.Capacity = this.Count;
            this._values.Capacity = this.Count;
            foreach (var kvp in this)
            {
                this._keys.Add(kvp.Key);
                this._values.Add(kvp.Value);
            }
        }

        public void OnAfterDeserialize()
        {
            // Debug.Log("OnAfterDeserialize");
            this.Clear();
            int count = Mathf.Min(this._keys.Count, this._values.Count);
            for (int i = 0; i < count; ++i)
            {
                this.Add(this._keys[i], this._values[i]);
            }
        }
    }
相关标签: unity