JsonUtility
CoddyのUnityジャーニー「Unityのゲームアーキテクチャ」セクションの一部。レッスン 30/64。
JSONはオブジェクトの値を保持するテキストなので、ログに記録したり、送信したり、ファイルに書き込んだりできます。JsonUtility.ToJson(obj)はオブジェクトをJSONに変換し、JsonUtility.FromJson<T>(json)はそこから新しいTを作成します。JsonUtilityはInspectorと同じルールに従うため、[System.Serializable]クラスで動作します。
[System.Serializable]
public class PlayerProfile
{
public string playerName = "Ana";
public int level = 7;
public List<string> badges = new List<string> { "Explorer", "Sharpshooter" };
[SerializeField] private float hoursPlayed = 12.5f;
private int secretCode = 1234;
public int Rank { get; set; } = 3;
}string json = JsonUtility.ToJson(new PlayerProfile());
// {"playerName":"Ana","level":7,"badges":["Explorer","Sharpshooter"],"hoursPlayed":12.5}
PlayerProfile copy = JsonUtility.FromJson<PlayerProfile>(json);secretCodeとRankは含まれていません。JsonUtilityが書き出すのは、パブリックフィールドと[SerializeField]が付いたプライベートフィールドだけです。それ以外は書き出しません。プロパティ、staticフィールド、通常のプライベートフィールドは対象外です。Dictionaryフィールドもスキップされ、クラスが[System.Serializable]ではないフィールドも同様です。Inspectorでも、これらのフィールドは表示されません。JsonUtility.ToJson(obj, true)を使うと、同じJSONが複数行にわたって書き出されるため、読みやすくなります。
クラス内のリストは、badgesのように書き出されます。一方、単独のリストは書き出されません。JsonUtilityは最上位にオブジェクトを必要とするため、10、20、30を含むList<int>に対してJsonUtility.ToJson(scores)を実行すると、{}が返されます。リストをクラスに入れてから変換しましょう。同じリストを保持するScoreBoardは、{"scores":[10,20,30]}として書き出されます。
[System.Serializable]
public class ScoreBoard
{
public List<int> scores;
}チャレンジ
中級チームをJSONコードとして共有します。
CharacterBuildで、Strengthをフィールドpublic int strength;にし、agilityに[SerializeField]を付けます。- その下に、
public List<CharacterBuild> heroes;を持つ[System.Serializable]クラスTeamを書きます。TeamCodeでは、リストをpublic Team team;にし、そのJSONをログに出力します。 LoadCodeはcodeをteamに読み込み、Loaded 3 heroesをログに出力します。
「プレイ」を押してスペースキーを押すと、チームがJSONとして表示されます。その後、「確認」を押します。
自分で試してみよう
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class CharacterBuild
{
public string hero;
public int Strength { get; set; }
private int agility;
}
Unityのゲームアーキテクチャのすべてのレッスン
自分で練習してみよう: Unityプレイグラウンド