Neodroid  0.2.0
Machine Learning Environment Prototyping Tool
SerializableDictionary.cs
Go to the documentation of this file.
1 using System.Collections.Generic;
2 using UnityEngine;
3 
4 namespace droid.Runtime.Utilities.ScriptableObjects.SerialisableDictionary {
5  public abstract class SerializableDictionary<TK, TV> : ISerializationCallbackReceiver {
6  public Dictionary<TK, TV> _Dict;
7  [SerializeField] TK[] _keys;
8 
9  [SerializeField] TV[] _values;
10 
11  public void OnAfterDeserialize() {
12  var c = this._keys.Length;
13  this._Dict = new Dictionary<TK, TV>(c);
14  for (var i = 0; i < c; i++) {
15  this._Dict[this._keys[i]] = this._values[i];
16  }
17 
18  this._keys = null;
19  this._values = null;
20  }
21 
22  public void OnBeforeSerialize() {
23  var c = this._Dict.Count;
24  this._keys = new TK[c];
25  this._values = new TV[c];
26  var i = 0;
27  using (var e = this._Dict.GetEnumerator()) {
28  while (e.MoveNext()) {
29  var kvp = e.Current;
30  this._keys[i] = kvp.Key;
31  this._values[i] = kvp.Value;
32  i++;
33  }
34  }
35  }
36 
37  public static T New<T>() where T : SerializableDictionary<TK, TV>, new() {
38  var result = new T {_Dict = new Dictionary<TK, TV>()};
39  return result;
40  }
41  }
42 }