SerializableHashSet.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #if UNITY_EDITOR
  2. using UnityEngine;
  3. using System;
  4. using System.Collections.Generic;
  5. namespace O3DWB
  6. {
  7. [Serializable]
  8. public class SerializableHashSet<SerializedType> : ISerializationCallbackReceiver
  9. where SerializedType : class
  10. {
  11. #region Private Variables
  12. private HashSet<SerializedType> _hashSet = new HashSet<SerializedType>();
  13. [SerializeField]
  14. private List<SerializedType> _serializedList = new List<SerializedType>();
  15. #endregion
  16. #region Public Properties
  17. public HashSet<SerializedType> HashSet { get { return _hashSet; } }
  18. public int Count { get { return HashSet.Count; } }
  19. #endregion
  20. #region Public Methods
  21. public void OnBeforeSerialize()
  22. {
  23. RemoveNullEntries();
  24. _serializedList.Clear();
  25. // Store the hash set values in the serialized list
  26. foreach (SerializedType serializedEntity in _hashSet)
  27. {
  28. _serializedList.Add(serializedEntity);
  29. }
  30. }
  31. public void OnAfterDeserialize()
  32. {
  33. // Create the hash set based on the serialized list
  34. _hashSet = new HashSet<SerializedType>(_serializedList);
  35. _serializedList.Clear();
  36. }
  37. public void RemoveNullEntries()
  38. {
  39. _hashSet.RemoveWhere(item => EqualityComparer<SerializedType>.Default.Equals(item, default(SerializedType)));
  40. }
  41. public bool Contains(SerializedType entity)
  42. {
  43. return _hashSet.Contains(entity);
  44. }
  45. public void Add(SerializedType entity)
  46. {
  47. _hashSet.Add(entity);
  48. }
  49. public void Remove(SerializedType entity)
  50. {
  51. _hashSet.Remove(entity);
  52. }
  53. public void RemoveWhere(Predicate<SerializedType> match)
  54. {
  55. _hashSet.RemoveWhere(match);
  56. }
  57. public void Clear()
  58. {
  59. _hashSet.Clear();
  60. }
  61. public void FromEnumerable(IEnumerable<SerializedType> entities)
  62. {
  63. _hashSet = new HashSet<SerializedType>(entities);
  64. }
  65. #endregion
  66. }
  67. }
  68. #endif