Created
February 26, 2024 05:42
-
-
Save zwcloud/530b705ecaadf24e28c710a43224a9bf to your computer and use it in GitHub Desktop.
Unity JsonUtility SerializableSortedList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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