I need a HashSet I can edit in the Inspector.
I've found this solution...
Posted here...
using System;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class SerializableHashSet<T> : HashSet<T>, ISerializationCallbackReceiver
{
[SerializeField]
private List<T> values = new List<T>();
public SerializableHashSet() : base() {}
public SerializableHashSet(IEnumerable<T> collection) : base(collection) {}
public void OnBeforeSerialize ()
{
var cur = new HashSet<T> (values);
foreach (var val in this) {
if (!cur.Contains (val)) {
values.Add (val);
}
}
}
public void OnAfterDeserialize ()
{
Clear ();
foreach (var val in values)
{
if (val != null)
Add (val);
}
}
}
However it throws the following 2 errors...
NullReferenceException: Object reference not set to an instance of an object
System.Collections.Generic.HashSet`1+Enumerator[T].MoveNext () (at <351e49e2a5bf4fd6beabb458ce2255f3>:0)
SerializableHashSet`1[T].OnBeforeSerialize () (at Assets/Scripts/Utilities/Collections/SerializableHashSet.cs:23)
ArgumentNullException: Value cannot be null.
Parameter name: array
System.Array.Clear (System.Array array, System.Int32 index, System.Int32 length) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Collections.Generic.HashSet`1[T].Clear () (at <351e49e2a5bf4fd6beabb458ce2255f3>:0)
SerializableHashSet`1[T].OnAfterDeserialize () (at Assets/Scripts/Utilities/Collections/SerializableHashSet.cs:32)
I'm also not sure I need the check on line 21 - Surely duplicates just wouldn't be in the internal HashSet in the first place?