mirror of
https://github.com/ConjureETS/Unity_Utils.git
synced 2026-03-23 20:40:58 +00:00
42 lines
1.1 KiB
C#
42 lines
1.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace JohnsonUtils.Utilities
|
|
{
|
|
[Serializable]
|
|
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
|
|
{
|
|
[SerializeField] private List<TKey> keys = new ();
|
|
[SerializeField] private List<TValue> values = new ();
|
|
|
|
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(
|
|
$"There are {keys.Count} keys and {values.Count} values after deserialization." +
|
|
" Make sure that both key and value types are serializable.");
|
|
}
|
|
|
|
for (int i = 0; i < keys.Count; ++i)
|
|
{
|
|
Add(keys[i], values[i]);
|
|
}
|
|
}
|
|
}
|
|
} |