ãUnityãJsonUtilityã使ã£ã¦ãã¼ã¿ãä¿åãã¦ã¿ã
Unity 2019.2.0f1 Personal(2019å¹´8æ)
Unityã§ã¯JsonUtilityã¨ããAPIã使ãã
Jsonï¼ãã¼ã¿ãã©ã¼ãããï¼ãæ±ããã¨ãåºæ¥ã¾ãã
ã¯ã©ã¹ãªã©ãã¼ã¿ã®ã¾ã¨ã¾ãããJsonããã¹ãã¸å¤æï¼ã·ãªã¢ã©ã¤ãºï¼ãããã
éã«Jsonããã¹ãããã¯ã©ã¹ã¸å¤æï¼ãã·ãªã¢ã©ã¤ãºï¼ãããã§ãã¾ãã
ã·ãªã¢ã©ã¤ãºï¼JsonUtility.ToJsonï¼
JsonUtilityã®ToJsonã¡ã½ããã§ã¯ã©ã¹âJsonã¸å¤æã§ãã¾ãã
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class SaveDataManager: MonoBehaviour { void Start() { var saveData = new SaveData(); string toData = JsonUtility.ToJson(saveData); Debug.Log(toData); } } [Serializable] class SaveData { public int id; public string name; public SaveData() { id = 1; name = "åç¡ã"; } }
SaveDataManager.cs
SaveDataã¯ã©ã¹ãã¤ã³ã¹ã¿ã³ã¹åãã
JsonUtility.ToJsonã¡ã½ãããéãã ãã§Jsonå½¢å¼ã®æååã«å¤æããã¾ãã
ã·ãªã¢ã©ã¤ãºããSaveDataã¯ã©ã¹ã«ã¯[Serializable]å±æ§ãã¤ãã¦ä¸ããã
ã¾ãã·ãªã¢ã©ã¤ãºã»ãã·ãªã¢ã©ã¤ãºãã対象ãã¼ã¿ã®å¤æ°å±æ§ã¯
publicã[Serialize Field]ã§ããå¿
è¦ãããã¾ãã
é©å½ãªãªãã¸ã§ã¯ãã«SaveDataManagerãã¤ãã¦å®è¡ããã¨Consoleã«Jsonãã¼ã¿ã表示ããã¾ãã
ãã·ãªã¢ã©ã¤ãºï¼JsonUtility.FromJsonï¼
ç¶ãã¦ã·ãªã¢ã©ã¤ãºããJsonãã¼ã¿ã
JsonUtility.FromJsonã¡ã½ããã§ãã·ãªã¢ã©ã¤ãºãã¯ã©ã¹ã«æ»ãã¾ãã
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class SaveDataManager: MonoBehaviour { void Start() { var saveData = new SaveData(); string toData = JsonUtility.ToJson(saveData); Debug.Log(toData); // ***** éå§ ***** var fromData = JsonUtility.FromJson<SaveData>(toData); Debug.Log(fromData.id + ":" + fromData.name); // ***** çµäº ***** } } [Serializable] class SaveData { public int id; public string name; public SaveData() { id = 1; name = "åç¡ã"; } }
SaveDataManager.cs
JsonUtility.FromJsonã¡ã½ããã¯ã¸ã§ããªã¯ã¹ï¼
ä»åã®å ´åã ã¨
SaveDataã«å«ã¾ããªãå¤ãJsonã«å«ã¾ããå ´åããã®å¤ã¯ç¡è¦ããã¾ãã
以ä¸ãJsonUtilityã®æ±ãæ¹ã§ããã