以下の内容はhttps://baba-s.hatenablog.com/entry/2020/01/30/090000より取得しました。


【Unity】HashSet を JsonUtility でシリアライズ・デシリアライズするサンプル

ソースコード

using System;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public sealed class Example : ISerializationCallbackReceiver
{
    [SerializeField] private int[] m_array = null;

    private HashSet<int> m_hashSet;

    public IReadOnlyCollection<int> HashSet => m_hashSet;

    public Example( IEnumerable<int> collection )
    {
        m_hashSet = new HashSet<int>( collection );
    }

    public void OnBeforeSerialize()
    {
        m_array = new int[m_hashSet.Count];
        m_hashSet.CopyTo( m_array );
    }

    public void OnAfterDeserialize()
    {
        m_hashSet = new HashSet<int>( m_array );
        m_array   = null;
    }
}

使用例

using UnityEngine;

public class Test : MonoBehaviour
{
    private void Start()
    {
        var data = new Example( new[] { 1, 2, 3 } );
        var json = JsonUtility.ToJson( data );

        // {"m_array":[1,2,3]}
        Debug.Log( json );

        var result = JsonUtility.FromJson<Example>( json );

        // 1
        // 2
        // 3
        foreach ( var n in result.HashSet )
        {
            Debug.Log( n );
        }
    }
}



以上の内容はhttps://baba-s.hatenablog.com/entry/2020/01/30/090000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14