using System;
using System.Collections.Generic;
using UnityEngine;
namespace OctoCore.Save
{
///
/// A dictionary that can be serialized by Unity.
/// Converts between Dictionary and List representations for Unity serialization.
///
/// The type of keys in the dictionary.
/// The type of values in the dictionary.
[Serializable]
public class OctoSerializableDictionary : ISerializationCallbackReceiver
{
[SerializeField] private List _keys = new();
[SerializeField] private List _values = new();
private Dictionary _dictionary = new();
///
/// Gets the underlying dictionary.
///
public Dictionary Dictionary => _dictionary;
///
/// Called before Unity serializes the object.
/// Converts the dictionary to lists for serialization.
///
public void OnBeforeSerialize()
{
_keys.Clear();
_values.Clear();
foreach (var kvp in _dictionary)
{
_keys.Add(kvp.Key);
_values.Add(kvp.Value);
}
}
///
/// Called after Unity deserializes the object.
/// Reconstructs the dictionary from serialized lists.
///
public void OnAfterDeserialize()
{
_dictionary = new Dictionary();
for (int i = 0; i < Math.Min(_keys.Count, _values.Count); i++)
{
_dictionary[_keys[i]] = _values[i];
}
}
///
/// Gets or sets the value associated with the specified key.
///
/// The key to access.
/// The value associated with the key, or default if not found.
public TValue this[TKey key]
{
get => _dictionary.ContainsKey(key) ? _dictionary[key] : default;
set => _dictionary[key] = value;
}
///
/// Determines whether the dictionary contains the specified key.
///
/// The key to locate.
/// True if the dictionary contains the key; otherwise, false.
public bool ContainsKey(TKey key) => _dictionary.ContainsKey(key);
///
/// Removes the value with the specified key from the dictionary.
///
/// The key of the element to remove.
public void Remove(TKey key) => _dictionary.Remove(key);
}
}