ソース
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Runtime.Serialization.Formatters.Binary; | |
using System.IO; | |
public class JsonTest : MonoBehaviour | |
{ | |
//--- | |
[System.Serializable] | |
public class Item | |
{ | |
public int id; | |
public string name; | |
public string description; | |
} | |
//--- | |
string savePath = "Assets/Test/JsonTest/saveData.json"; | |
// Use this for initialization | |
void Start () | |
{ | |
string itemJson = "{ \"id\": 100, \"name\": \"テストアイテム\", \"description\": \"説明だよ\" }"; | |
Item item = JsonUtility.FromJson<Item>(itemJson); | |
save(item); | |
TestLog(item); | |
Debug.Log("---"); | |
item = load(); | |
TestLog(item); | |
} | |
//セーブ | |
private void save(Item item) | |
{ | |
string json = JsonUtility.ToJson(item); | |
BinaryFormatter bf = new BinaryFormatter(); | |
FileStream file = File.Create(savePath); | |
bf.Serialize(file, json); | |
file.Close(); | |
} | |
//ロード | |
private Item load() | |
{ | |
BinaryFormatter bf = new BinaryFormatter(); | |
FileStream file = File.Open(savePath, FileMode.Open); | |
string json = (string)bf.Deserialize(file); | |
file.Close(); | |
return JsonUtility.FromJson<Item>(json); | |
} | |
//確認用のログを表示 | |
private void TestLog(Item item) | |
{ | |
Debug.Log("item id " + item.id); | |
Debug.Log("item name " + item.name); | |
Debug.Log("item description " + item.description); | |
} | |
} |
実行結果
尚、unityのエディタ上にファイルが表示されるのには少し時間がかかった。
0 件のコメント:
コメントを投稿