// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEngine; namespace AWS.GameKit.Runtime.Utils { [Serializable] public class SerializableDictionary : Dictionary, ISerializationCallbackReceiver { public List ListOfSerializedValues => _values; public string NameOfSerializedValuesList => nameof(_values); [HideInInspector] [SerializeField] private List _keys = new List(); [HideInInspector] [SerializeField] private List _values = new List(); /// /// Since a Dictionary is not Serializable in C# by default we breakout the KVPs that were stored in the dictionary into a key list and value list which can be Serialized.

/// /// OnBeforeSerialize will run whenever the SerializableDictionary is trying to be Serialized. ///
public void OnBeforeSerialize() { _keys.Clear(); _values.Clear(); foreach (var kvp in this) { _keys.Add(kvp.Key); _values.Add(kvp.Value); } } /// /// Since a Dictionary is not Serializable in C# by default we take a list of keys and list of values that were serialized in OnBeforeSerialize() and turn them back into a dictionary.

/// /// OnAfterDeserialize will run whenever the SerializableDictionary is trying to be Deserialized. ///
public void OnAfterDeserialize() { Clear(); if (_keys.Count != _values.Count) { Logging.LogError($"There were {_keys.Count} keys and {_values.Count} values found while deserializing the SerializableDictionary. This SerializableDictionary may contain inaccurate data."); } int lowestCount = Math.Min(_keys.Count, _values.Count); for (int i = 0; i != lowestCount; i++) { Add(_keys[i], _values[i]); } } /// /// Gets a value from the dictionary.

/// /// Note: If the key does not exist yet, will first add the key with a initial value of new V(). ///
/// The key in the dictionary that holds the desired value. /// public V GetValue(K key) { if (!this.ContainsKey(key)) { this.Add(key, default); } return this[key]; } /// /// Adds a key value pair to the dictionary.

/// /// Note: If the key does not exist in the dictionary, will add it. ///
/// The key in the dictionary that should hold the passed in value. /// The new value the key should be matched to. public void SetValue(K key, V value) { if (!this.ContainsKey(key)) { this.Add(key, value); } this[key] = value; } } }