Skip to content

Instantly share code, notes, and snippets.

@zwcloud
Created February 26, 2024 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zwcloud/530b705ecaadf24e28c710a43224a9bf to your computer and use it in GitHub Desktop.
Save zwcloud/530b705ecaadf24e28c710a43224a9bf to your computer and use it in GitHub Desktop.
Unity JsonUtility SerializableSortedList
[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>();
// Unity serialization callback before serialization
public void OnBeforeSerialize()
{
keys.Clear();
values.Clear();
foreach (var kvp in this)
{
keys.Add(kvp.Key);
values.Add(kvp.Value);
}
}
// Unity serialization callback after deserialization
public void OnAfterDeserialize()
{
this.Clear();
if (keys.Count != values.Count)
{
throw new Exception("The number of keys and values in the SortedList do not match.");
}
for (int i = 0; i < keys.Count; i++)
{
this[keys[i]] = values[i];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment