コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【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 );
        }
    }
}