ScenePartition/Runtime/SerializationUtility.cs

101 lines
2.5 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using UnityEngine;
namespace VertexColor.ScenePartition
{
[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()
{
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("Error: Key and value count does not match in the dictionary.");
}
for (int i = 0; i < keys.Count; i++)
{
Add(keys[i], values[i]);
}
}
}
[Serializable]
public class SerializableSortedList<TKey, TValue> : SortedList<TKey, TValue>, ISerializationCallbackReceiver
{
[SerializeField]
private List<TKey> keys = new List<TKey>();
[SerializeField]
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("Error: Key and value count does not match in the dictionary.");
}
for (int i = 0; i < keys.Count; i++)
{
Add(keys[i], values[i]);
}
}
}
[Serializable]
public class SerializableSortedSet<T> : SortedSet<T>, ISerializationCallbackReceiver
{
[SerializeField]
private List<T> elements = new List<T>();
public void OnBeforeSerialize()
{
elements.Clear();
elements.AddRange(this);
}
public void OnAfterDeserialize()
{
Clear();
for (int i = 0; i < elements.Count; i++)
{
Add(elements[i]);
}
}
}
}