@@ -7,6 +7,7 @@ namespace UnityEngine
77{
88 /// <summary>
99 /// Overlay for the <see cref="Dictionary{TKey, TValue}"/> to allow serialization of the key/value pairs.
10+ /// Highly suggested to cast it to a <see cref="Dictionary{TKey, TValue}"/> when used in runtime.
1011 /// </summary>
1112 [ Serializable ]
1213 public sealed class SerializedDictionary < TK , TV > : IDictionary < TK , TV > , ISerializationCallbackReceiver
@@ -38,7 +39,6 @@ public TV Value
3839 }
3940 }
4041
41-
4242 [ SerializeField ]
4343 private List < KeyValuePair > pairs = new List < KeyValuePair > ( ) ;
4444
@@ -48,6 +48,16 @@ public TV Value
4848 [ SerializeField , HideInInspector ]
4949 private bool error ;
5050
51+ public SerializedDictionary ( )
52+ { }
53+
54+ public SerializedDictionary ( IDictionary < TK , TV > source )
55+ {
56+ foreach ( var pair in source )
57+ {
58+ Add ( pair . Key , pair . Value ) ;
59+ }
60+ }
5161
5262 private void UpdateIndexes ( int removedIndex )
5363 {
@@ -58,8 +68,8 @@ private void UpdateIndexes(int removedIndex)
5868 }
5969 }
6070
61-
62- void ISerializationCallbackReceiver . OnBeforeSerialize ( ) { }
71+ void ISerializationCallbackReceiver . OnBeforeSerialize ( )
72+ { }
6373
6474 void ISerializationCallbackReceiver . OnAfterDeserialize ( )
6575 {
@@ -122,6 +132,9 @@ public void Clear()
122132 indexByKey . Clear ( ) ;
123133 }
124134
135+ /// <summary>
136+ /// Creates a new instance of <see cref="Dictionary{TKey, TValue}"/> using the internally serialized data.
137+ /// </summary>
125138 public Dictionary < TK , TV > BuildNativeDictionary ( )
126139 {
127140 return new Dictionary < TK , TV > ( dictionary ) ;
@@ -174,7 +187,6 @@ IEnumerator IEnumerable.GetEnumerator()
174187 return dictionary . GetEnumerator ( ) ;
175188 }
176189
177-
178190 /// <summary>
179191 /// Indicates if there is a key collision in serialized pairs.
180192 /// Duplicated keys (pairs) won't be added to the final dictionary.
@@ -187,8 +199,6 @@ internal bool Error
187199
188200 public int Count => dictionary . Count ;
189201
190- public bool IsReadOnly => false ;
191-
192202 public ICollection < TK > Keys => dictionary . Keys ;
193203
194204 public ICollection < TV > Values => dictionary . Values ;
@@ -211,6 +221,18 @@ public TV this[TK key]
211221 }
212222 }
213223 }
224+
225+ public bool IsReadOnly => false ;
226+
227+ public static implicit operator Dictionary < TK , TV > ( SerializedDictionary < TK , TV > serializedDictionary )
228+ {
229+ return serializedDictionary . dictionary ;
230+ }
231+
232+ public static implicit operator SerializedDictionary < TK , TV > ( Dictionary < TK , TV > dictionary )
233+ {
234+ return new SerializedDictionary < TK , TV > ( dictionary ) ;
235+ }
214236 }
215237}
216238#endif
0 commit comments