Created
September 16, 2022 18:16
-
-
Save ratozumbi/9af6adca4d8ec521b7deef64712601c2 to your computer and use it in GitHub Desktop.
WIP serializable dictionary
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
#nullable enable | |
using System; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public interface ISerializableDictionaryKey | |
{ | |
public ISerializableDictionaryKey GetNewKey(); | |
} | |
public interface ISerializableDictionaryValue | |
{ | |
public ISerializableDictionaryValue GetNewValue(); | |
} | |
[Serializable] | |
public class SerializableDictionary<TK, TV> : Dictionary<TK, TV?>, ISerializationCallbackReceiver where TK:ISerializableDictionaryKey where TV:ISerializableDictionaryValue | |
{ | |
[SerializeField] | |
[Tooltip("Control dictionary size using this size")] | |
private List<TK> _keys = new List<TK>(); | |
[SerializeField] | |
[Tooltip("Don't change this size. Control dictionary size using Keys size")] | |
private List<TV> _values = new List<TV>(); | |
// save the dictionary to lists | |
public void OnBeforeSerialize() | |
{ | |
_keys.Clear(); | |
_values.Clear(); | |
foreach(KeyValuePair<TK, TV> pair in this) | |
{ | |
_keys.Add(pair.Key); | |
_values.Add(pair.Value); | |
} | |
} | |
// load dictionary from lists | |
public void OnAfterDeserialize() | |
{ | |
bool isAddingEntry = _keys.Count > _values.Count;// (tempDic._keys.Count > _keys.Count || tempDic._values.Count > _keys.Count); | |
this.Clear(); | |
if (isAddingEntry) | |
{ | |
for (int i = 0; i < Math.Max(_keys.Count,_values.Count); i++) | |
{ | |
if (i >= _values.Count) | |
{ | |
this.Add((TK)_keys[0].GetNewKey(),(TV)_values[0].GetNewValue());//TODO: this in not going to work | |
} | |
else | |
{ | |
this.Add(_keys[i], _values[i]); | |
} | |
} | |
} | |
if (!isAddingEntry) | |
{ | |
for (int i = 0; i < Math.Min(_keys.Count,_values.Count); i++) | |
{ | |
this.Add(_keys[i], _values[i]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment