コガネブログ

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

【Unity】Dictionary を JsonUtility で変換できるようにするクラス

ソースコード

使用例

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

public class Example : MonoBehaviour
{
    private void Awake()
    {
        var dictionary1 = new Dictionary<int, string>()
        {
            { 1, "フシギダネ" },
            { 2, "フシギソウ" },
            { 3, "フシギバナ" },
        };

        var jsonDictionary1 = new JsonDictionary<int, string>( dictionary1 );
        var json            = JsonUtility.ToJson( jsonDictionary1, true );

        Debug.Log( json );

        var jsonDictionary2 = JsonUtility.FromJson<JsonDictionary<int, string>>( json );
        var dictionary2     = jsonDictionary2.Dictionary;

        foreach ( var x in dictionary2 )
        {
            Debug.Log( x.Key + ": " + x.Value );
        }
    }
}