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