47 lines
1.0 KiB
C#
47 lines
1.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.Serialization;
|
|
|
|
namespace OHM.UnityToolkit
|
|
{
|
|
[Serializable]
|
|
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
|
|
{
|
|
[SerializeField]
|
|
[FormerlySerializedAs("keys")]
|
|
private List<TKey> _keys = new List<TKey>();
|
|
|
|
[SerializeField]
|
|
[FormerlySerializedAs("values")]
|
|
private List<TValue> _values = new List<TValue>();
|
|
|
|
public void OnBeforeSerialize()
|
|
{
|
|
_keys.Clear();
|
|
_values.Clear();
|
|
foreach (KeyValuePair<TKey, TValue> pair in this)
|
|
{
|
|
_keys.Add(pair.Key);
|
|
_values.Add(pair.Value);
|
|
}
|
|
}
|
|
|
|
public void OnAfterDeserialize()
|
|
{
|
|
Clear();
|
|
if (_keys.Count != _values.Count)
|
|
{
|
|
throw new Exception(string.Format(
|
|
"there are {0} _keys and {1} _values after deserialization. Make sure that both key and value"
|
|
+ " types are serializable.", _keys.Count, _values.Count));
|
|
}
|
|
for (int i = 0; i < _keys.Count; i++)
|
|
{
|
|
Add(_keys[i], _values[i]);
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|