【发布时间】:2021-12-08 18:08:15
【问题描述】:
我需要一个可以在 Inspector 中编辑的 HashSet。
我找到了this solution...
在这里发布...
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);
}
}
}
但是它会引发以下 2 个错误...
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)
我也不确定我是否需要在第 21 行检查 - 肯定重复只是首先不会出现在内部 HashSet 中?
【问题讨论】:
标签: c# unity3d serialization deserialization hashset